NOTE: this feature may still be changed before we formally release 1.1.
A snippet for creating a login form is as follows:
// --- login action ---
// the configuration describing the form
// this is an array of name-value pairs
// used to initialize the properties of CForm
// Please check CForm's API for how to configure
// 'elements' and 'buttons'
$config=array(
'elements'=>array(
'username'=>array(
'type'=>'text',
),
'password'=>array(
'type'=>'password',
),
'rememberMe'=>array(
'type'=>'checkbox',
)
),
'buttons'=>array(
'login'=>array(
'type'=>'submit',
'label'=>'Login',
),
),
);
// generate the form using the above config
// and the LoginForm model
$form=new CForm($config, new LoginForm);
// check if the form is submitted and the inputs are valid
if($form->submitted() && $form->validate())
$this->redirect(array('site/index'));
$this->render('login', array('form'=>$form));
// --- login view ---
<h1>Login</h1>
<?php echo $form; ?>
In the above, the form configuration may be stored in a separate file or be returned by the model class.
Themain benefit of using form builder is the separation of logic(elements, buttons) and presentation (how to render thoseelements/buttons).
As a result, we can extend CForm or use differentviews to render a form object so that the same set of elements/buttonscan be rendered differently and in a consistent way across the wholeapplication.
How do you add a preview ability using the form builder? I can’t work out how to get the values submitted in the view. They all seem to be under “_model”:“CForm”:private.
public function actionLogin()
{
$model = new LoginForm;
$form = new CForm('application.views.forms.LoginForm', $model);
if($form->submitted() && $form->validate())
{
$this->redirect(Yii::app()->user->returnUrl);
}else{
// display the login form
$this->render('login',array('form'=>$form));
}
}
upon inspecting CForm::submitted(), i realized it method accepts the name of the button as a parameter
public function submitted($buttonName='submit',$loadData=true)
{
$ret=$this->clicked($this->getUniqueId()) && $this->clicked($buttonName);
if($ret && $loadData)
$this->loadData();
return $ret;
}
which defaults to ‘submit’ if not specified.
in the example you have in the documentation you should either pass ‘login’ to the CForm::submitted() or change the button from ‘login’ to submit in the form defenition.