CActiveForm

Package system.web.widgets
Inheritance class CActiveForm » CWidget » CBaseController » CComponent
Subclasses CCodeForm
Since 1.1.1
Version $Id: CActiveForm.php 2104 2010-05-06 20:52:29Z qiang.xue $
CActiveForm provides a set of methods that can facilitate creating a form associated with some data models.

CActiveForm implements a set of wrapper methods that call the corresponding 'active' methods in CHtml. For example, the textField method is a wrapper of CHtml::activeTextField.

The 'beginWidget' and 'endWidget' call of CActiveForm widget will render the open and close form tags. Anything in between are rendered as form content (such as input fields, labels). We can call the wrapper methods of CActiveForm to generate these form contents. For example, calling CActiveForm::textField, which is a wrapper of CHtml::activeTextField, would generate an input field for a specified model attribute.

Besides the wrapper methods, CActiveForm also implements an important feature known as AJAX validation. This feature may be turned on setting enableAjaxValidation to be true. When the user enters some value in an input field, the AJAX validation feature would trigger an AJAX request to the server to call for validating the model with the current user inputs. If there are any validation errors, the corresponding error messages will show up next to the input fields immediately.

The AJAX validation feature may greatly improve the user experience at entering data into a form. Because the validation is done on the server side using the rules defined in the data model, no extra javascript code needs to be written. More importantly, and the validation result is consistent with the server-side validation. And in case when the user turns off javascript in his browser, it automatically falls back to traditional validation via whole page submission.

To use CActiveForm with AJAX validation, one needs to write both the view code and the controller action code.

The following is a piece of sample view code:
<?php $form = $this->beginWidget('CActiveForm', array(
    'id'=>'user-form',
    'enableAjaxValidation'=>true,
)); ?>

<?php echo $form->errorSummary($model); ?>

<div class="row">
    <?php echo $form->labelEx($model,'firstName'); ?>
    <?php echo $form->textField($model,'firstName'); ?>
    <?php echo $form->error($model,'firstName'); ?>
</div>
<div class="row">
    <?php echo $form->labelEx($model,'lastName'); ?>
    <?php echo $form->textField($model,'lastName'); ?>
    <?php echo $form->error($model,'lastName'); ?>
</div>

<?php $this->endWidget(); ?>


To respond to the AJAX validation requests, we need the following class code:
public function actionCreate()
{
    $model=new User;
    $this->performAjaxValidation($model);
    if(isset($_POST['User']))
    {
        $model->attributes=$_POST['User'];
        if($model->save())
            $this->redirect('index');
    }
    $this->render('create',array('model'=>$model));
}

protected function performAjaxValidation($model)
{
    if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
    {
        echo CActiveForm::validate($model);
        Yii::app()->end();
    }
}
The method performAjaxValidation is the main extra code we add to our traditional model creation action code. In this method, we check if the request is submitted via AJAX by the 'user-form'. If so, we validate the model and return the validation results. We may call the same method in model update action.

On the client side, an input field may be in one of the four states: initial (not validated), validating, error and success. To differentiate these states, CActiveForm automatically assigns different CSS classes for the last three states to the HTML element containing the input field. By default, these CSS classes are named as 'validating', 'error' and 'success', respectively. They may be changed by configuring the options property or specifying in the error method.

Sometimes, we may want to limit the AJAX validation to certain model attributes only. This can be achieved by setting the model with a scenario that is specific for AJAX validation. Then only list those attributes that need AJAX validation in the scenario in CModel::rules() declaration.

There are some limitations of CActiveForm regarding to its AJAX validation support. First, it does not validate with file upload fields. Second, it should not be used to perform validations that may cause server-side state change. For example, it is not suitable to perform CAPTCHA validation done by CCaptchAction because each validation request will increase the number of tests by one. Third, it is not designed to work with tabular data input for the moment.

Because CActiveForm relies on submitting the whole form in AJAX mode to perform the validation, if the form has a lot of data to submit, the performance may not be good. In this case, you should design your own lightweight AJAX validation.

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
action mixed the form action URL (see normalizeUrl for details about this parameter. CActiveForm
actionPrefix string the prefix to the IDs of the actions. CWidget
clientOptions array the options to be passed to the javascript validation plugin. CActiveForm
controller CController the controller that this widget belongs to. CWidget
enableAjaxValidation boolean whether to enable data validation via AJAX. CActiveForm
errorMessageCssClass string the CSS class name for error messages. CActiveForm
htmlOptions array additional HTML attributes that should be rendered for the form tag. CActiveForm
id string id of the widget. CWidget
method string the form submission method. CActiveForm
owner CBaseController owner/creator of this widget. CWidget
skin mixed the name of the skin to be used by this widget. CWidget
stateful boolean whether to generate a stateful form (See CHtml::statefulForm). CActiveForm
viewPath string Returns the directory containing the view files for this widget. CWidget

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. CComponent
__construct() Constructor. CWidget
__get() Returns a property value, an event handler list or a behavior based on its name. CComponent
__isset() Checks if a property value is null. CComponent
__set() Sets value of a component property. CComponent
__unset() Sets a component property to be null. CComponent
actions() Returns a list of actions that are used by this widget. CWidget
asa() Returns the named behavior object. CComponent
attachBehavior() Attaches a behavior to this component. CComponent
attachBehaviors() Attaches a list of behaviors to the component. CComponent
attachEventHandler() Attaches an event handler to an event. CComponent
beginCache() Begins fragment caching. CBaseController
beginClip() Begins recording a clip. CBaseController
beginContent() Begins the rendering of content that is to be decorated by the specified view. CBaseController
beginWidget() Creates a widget and executes it. CBaseController
canGetProperty() Determines whether a property can be read. CComponent
canSetProperty() Determines whether a property can be set. CComponent
checkBox() Renders a checkbox for a model attribute. CActiveForm
checkBoxList() Renders a checkbox list for a model attribute. CActiveForm
createWidget() Creates a widget and initializes it. CBaseController
detachBehavior() Detaches a behavior from the component. CComponent
detachBehaviors() Detaches all behaviors from the component. CComponent
detachEventHandler() Detaches an existing event handler. CComponent
disableBehavior() Disables an attached behavior. CComponent
disableBehaviors() Disables all behaviors attached to this component. CComponent
enableBehavior() Enables an attached behavior. CComponent
enableBehaviors() Enables all behaviors attached to this component. CComponent
endCache() Ends fragment caching. CBaseController
endClip() Ends recording a clip. CBaseController
endContent() Ends the rendering of content. CBaseController
endWidget() Ends the execution of the named widget. CBaseController
error() Displays the first validation error for a model attribute. CActiveForm
errorSummary() Displays a summary of validation errors for one or several models. CActiveForm
evaluateExpression() Evaluates a PHP expression or callback under the context of this component. CComponent
fileField() Renders a file field for a model attribute. CActiveForm
getController() CWidget
getEventHandlers() Returns the list of attached event handlers for an event. CComponent
getId() CWidget
getOwner() CWidget
getViewFile() Looks for the view script file according to the view name. CWidget
getViewPath() Returns the directory containing the view files for this widget. CWidget
hasEvent() Determines whether an event is defined. CComponent
hasEventHandler() Checks whether the named event has attached handlers. CComponent
hasProperty() Determines whether a property is defined. CComponent
hiddenField() Renders a hidden field for a model attribute. CActiveForm
init() Initializes the widget. CActiveForm
label() Renders an HTML label for a model attribute. CActiveForm
labelEx() Renders an HTML label for a model attribute. CActiveForm
listBox() Renders a list box for a model attribute. CActiveForm
passwordField() Renders a password field for a model attribute. CActiveForm
radioButton() Renders a radio button for a model attribute. CActiveForm
radioButtonList() Renders a radio button list for a model attribute. CActiveForm
raiseEvent() Raises an event. CComponent
render() Renders a view. CWidget
renderFile() Renders a view file. CBaseController
renderInternal() Renders a view file. CBaseController
run() Runs the widget. CActiveForm
setId() CWidget
textArea() Renders a text area for a model attribute. CActiveForm
textField() Renders a text field for a model attribute. CActiveForm
validate() Validates one or several models and returns the results in JSON format. CActiveForm
widget() Creates a widget and executes it. CBaseController

Property Details

action property
public mixed $action;

the form action URL (see normalizeUrl for details about this parameter.) If not set, the current page URL is used.

clientOptions property
public array $clientOptions;

the options to be passed to the javascript validation plugin. The following options are supported:



Some of the above options may be overridden in individual calls of error(). They include: validationDelay, validateOnChange, validateOnType, hideErrorMessage, inputContainer, errorCssClass, successCssClass, validatingCssClass, beforeValidateAttribute, afterValidateAttribute.

enableAjaxValidation property
public boolean $enableAjaxValidation;

whether to enable data validation via AJAX. Defaults to false. When this property is set true, you should

errorMessageCssClass property
public string $errorMessageCssClass;

the CSS class name for error messages. Defaults to 'errorMessage'. Individual error call may override this value by specifying the 'class' HTML option.

htmlOptions property
public array $htmlOptions;

additional HTML attributes that should be rendered for the form tag.

method property
public string $method;

the form submission method. This should be either 'post' or 'get'. Defaults to 'post'.

stateful property
public boolean $stateful;

whether to generate a stateful form (See CHtml::statefulForm). Defaults to false.

Method Details

checkBox() method
public void checkBox($model, $attribute, $htmlOptions=array ( ))
$model
$attribute
$htmlOptions

Renders a checkbox for a model attribute. This method is a wrapper of CHtml::activeCheckBox. Please check CHtml::activeCheckBox for detailed information about the parameters for this method.

checkBoxList() method
public void checkBoxList($model, $attribute, $data, $htmlOptions=array ( ))
$model
$attribute
$data
$htmlOptions

Renders a checkbox list for a model attribute. This method is a wrapper of CHtml::activeCheckBoxList. Please check CHtml::activeCheckBoxList for detailed information about the parameters for this method.

public void dropDownList($model, $attribute, $data, $htmlOptions=array ( ))
$model
$attribute
$data
$htmlOptions

Renders a dropdown list for a model attribute. This method is a wrapper of CHtml::activeDropDownList. Please check CHtml::activeDropDownList for detailed information about the parameters for this method.

error() method
public string error(CModel $model, string $attribute, array $htmlOptions=array ( ), boolean $enableAjaxValidation=true)
$model CModel the data model
$attribute string the attribute name
$htmlOptions array additional HTML attributes to be rendered in the container div tag. Besides all those options available in CHtml::error, the following options are recognized in addition:
  • validationDelay
  • validateOnChange
  • validateOnType
  • hideErrorMessage
  • inputContainer
  • errorCssClass
  • successCssClass
  • validatingCssClass
  • beforeValidateAttribute
  • afterValidateAttribute
These options override the corresponding options as declared in options for this particular model attribute. For more details about these options, please refer to clientOptions. Note that these options are only used when enableAjaxValidation is set true.
$enableAjaxValidation boolean whether to enable AJAX validation for the specified attribute. Note that in order toe enable AJAX validation, both enableAjaxValidation and this parameter must be true.
{return} string the validation result (error display or success message).

Displays the first validation error for a model attribute. This is similar to CHtml::error except that it registers the model attribute so that if its value is changed by users, an AJAX validation may be triggered.

See Also

errorSummary() method
public string errorSummary(mixed $models, string $header=NULL, string $footer=NULL, array $htmlOptions=array ( ))
$models mixed the models whose input errors are to be displayed. This can be either a single model or an array of models.
$header string a piece of HTML code that appears in front of the errors
$footer string a piece of HTML code that appears at the end of the errors
$htmlOptions array additional HTML attributes to be rendered in the container div tag.
{return} string the error summary. Empty if no errors are found.

Displays a summary of validation errors for one or several models. This method is very similar to CHtml::errorSummary except that it also works when AJAX validation is performed.

fileField() method
public void fileField($model, $attribute, $htmlOptions=array ( ))
$model
$attribute
$htmlOptions

Renders a file field for a model attribute. This method is a wrapper of CHtml::activeFileField. Please check CHtml::activeFileField for detailed information about the parameters for this method.

hiddenField() method
public void hiddenField($model, $attribute, $htmlOptions=array ( ))
$model
$attribute
$htmlOptions

Renders a hidden field for a model attribute. This method is a wrapper of CHtml::activeHiddenField. Please check CHtml::activeHiddenField for detailed information about the parameters for this method.

init() method
public void init()

Initializes the widget. This renders the form open tag.

label() method
public void label($model, $attribute, $htmlOptions=array ( ))
$model
$attribute
$htmlOptions

Renders an HTML label for a model attribute. This method is a wrapper of CHtml::activeLabel. Please check CHtml::activeLabel for detailed information about the parameters for this method.

labelEx() method
public void labelEx($model, $attribute, $htmlOptions=array ( ))
$model
$attribute
$htmlOptions

Renders an HTML label for a model attribute. This method is a wrapper of CHtml::activeLabelEx. Please check CHtml::activeLabelEx for detailed information about the parameters for this method.

listBox() method
public void listBox($model, $attribute, $data, $htmlOptions=array ( ))
$model
$attribute
$data
$htmlOptions

Renders a list box for a model attribute. This method is a wrapper of CHtml::activeListBox. Please check CHtml::activeListBox for detailed information about the parameters for this method.

passwordField() method
public void passwordField($model, $attribute, $htmlOptions=array ( ))
$model
$attribute
$htmlOptions

Renders a password field for a model attribute. This method is a wrapper of CHtml::activePasswordField. Please check CHtml::activePasswordField for detailed information about the parameters for this method.

radioButton() method
public void radioButton($model, $attribute, $htmlOptions=array ( ))
$model
$attribute
$htmlOptions

Renders a radio button for a model attribute. This method is a wrapper of CHtml::activeRadioButton. Please check CHtml::activeRadioButton for detailed information about the parameters for this method.

radioButtonList() method
public void radioButtonList($model, $attribute, $data, $htmlOptions=array ( ))
$model
$attribute
$data
$htmlOptions

Renders a radio button list for a model attribute. This method is a wrapper of CHtml::activeRadioButtonList. Please check CHtml::activeRadioButtonList for detailed information about the parameters for this method.

run() method
public void run()

Runs the widget. This registers the necessary javascript code and renders the form close tag.

textArea() method
public void textArea($model, $attribute, $htmlOptions=array ( ))
$model
$attribute
$htmlOptions

Renders a text area for a model attribute. This method is a wrapper of CHtml::activeTextArea. Please check CHtml::activeTextArea for detailed information about the parameters for this method.

textField() method
public void textField($model, $attribute, $htmlOptions=array ( ))
$model
$attribute
$htmlOptions

Renders a text field for a model attribute. This method is a wrapper of CHtml::activeTextField. Please check CHtml::activeTextField for detailed information about the parameters for this method.

validate() method
public static string validate(mixed $models, array $attributes=NULL, boolean $loadInput=true)
$models mixed a single model instance or an array of models.
$attributes array list of attributes that should be validated. Defaults to null, meaning any attribute listed in the applicable validation rules of the models should be validated. If this parameter is given as a list of attributes, only the listed attributes will be validated.
$loadInput boolean whether to load the data from $_POST array in this method. If this is true, the model will be populated from $_POST[ModelClass].
{return} string the JSON representation of the validation error messages.

Validates one or several models and returns the results in JSON format. This is a helper method that simplies the way of writing AJAX validation code.