CActiveForm or CForm?

Sorry for stupid question: what’s differences between CActiveForm and CForm? When I have to use one or the other?

Q#2: I think Form.builder is very cool. Personally I prefer it to the classic system, but I’ve noticed that in Gii is using the classic one to generate forms. So, for the future, is it better to use form.builder or remain to the classic?

TIA

Danilo

Q#1: The main difference is that CActiveForm can perform ajax validation (build in) while CForm can’t (you’ll have to develop that yourself).

Next to that, CActiveForm is derived from CWidget and can therefore benefit from the pro’s of a widget, i.e. it has it’s own set of controller actions. CForm is derived from CFormElement.

Q#2: Good question. I’d like to know this, too.

Answering both questions:

  1. You can do this easily bu specifying config property for the CForm: http://www.yiiframework.com/doc/api/CForm#activeForm-detail

Here’s the code that does the same as auto-generated login form does:

  • SiteController

public function actionLogin() {

		$model=new LoginForm;


		// if it is ajax validation request

		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form') {

			echo CActiveForm::validate($model);

			Yii::app()->end();

		}


		// collect user input data

		if(isset($_POST['LoginForm'])) {

			$model->attributes=$_POST['LoginForm'];

			// validate user input and redirect to the previous page if valid

			if($model->validate() && $model->login())

				$this->redirect(Yii::app()->user->returnUrl);

		}

		// display the login form

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

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

	}

  • loginForm.php

<?php

return array(

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

	'activeForm' => array(

			'class' => 'CActiveForm',

			'enableAjaxValidation' => true,

			'id' => 'login-form',

		),

    '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',

        ),

    ),

);

?>

That’s it. Key points:

  • You validate using model, not CForm. You can use the latter, but I don’t see any benefit in this. Maybe I’m mistaken

  • You specify the config for the CActiveFrom widget in the form config.

  1. This depends on the app. I’m pretty sure Yii will generate form configs in the future. I am going to use CForms in my projects.