Help with Cform

I really tried hard to follow the tutorial in the definitive guide to Yii and it is not really clear to me exactly how to implement this tool.

Step 1 is straightforward. It shows a controller script as follows:


public function actionLogin()

{

    $model = new LoginForm;

    $form = new CForm('application.views.site.loginForm', $model);

    if($form->submitted('login') && $form->validate())

        $this->redirect(array('site/index'));

    else

        $this->render('login', array('form'=>$form));

}

Step 2 describes a configuration array of elements to be returned back to the controller:




return array(

    'title'=>'Please provide your login credential',

 

    'elements'=>array(

        'username'=>array(

            'type'=>'text',

            'maxlength'=>32,

        ),

        'password'=>array(

            'type'=>'password',

            'maxlength'=>32,

        ),

        'rememberMe'=>array(

            'type'=>'checkbox',

        )

    ),

 

    'buttons'=>array(

        'login'=>array(

            'type'=>'submit',

            'label'=>'Login',

        ),

    ),

);



Then in step 3 there is a sample code for the view file which does not include any code other than the following:




<h1>Login</h1>

 

<div class="form">

<?php echo $form; ?>

</div>




There are a few things that aren’t making sense here. First of all, when I tried to run this script as is, I got an error “$form variable undefined” referencing the view file. The other issue is what happened to the element array? Where is that supposed to be? It is completely missing from the picture in the actual implementation. Is that defined in the loginForm model or in some function in the controller? This may seem obvious to some of you but I am just starting out here so any help would be appreciated.

OK, I have to admit that i haven’t ever use CForm as far and I was struggling to understand your issue since i was in the same trap and got the same error message by wrong use of CForm.

afer a bit research, here is how i made it work:

step2 in protected/views/site/loginForm.php


<?php

return array(

	'title'=>'Please provide your login credential',


	'elements'=>array(

		'username'=>array(

			'type'=>'text',

			'maxlength'=>32,

		),

		'password'=>array(

			'type'=>'password',

			'maxlength'=>32,

		),

		'rememberMe'=>array(

			'type'=>'checkbox',

		)

	),


	'buttons'=>array(

		'login'=>array(

			'type'=>'submit',

			'label'=>'Login',

		),

	),

);



basically it’s the description of a form which in my understanding is the same as view (protected/views/site/login.php) itself.

this is just how Yii trying to separate more logic form view to use CForm with configure array to describe view rather than ‘hardcode’ form elements in view.

I read Qiang ever mentioned that in Yii version 2.0, view will be a class. (lost the link to the post)

Read this, it’s more much clear for CForm example than that.