ActiveForm
API reference › yii › widgets › ActiveForm
1 subclass
ActiveForm is a widget that builds an interactive HTML form for one or multiple data models.
For more details and usage information on ActiveForm, see the guide article on forms.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$action | array| | The form action URL. Default: ''. | ActiveForm |
$ajaxDataType | string | The type of data that you’re expecting back from the server. Default: 'json'. | ActiveForm |
$ajaxParam | string | The name of the GET parameter indicating the validation request is an AJAX request. Default: 'ajax'. | ActiveForm |
$autoIdPrefix static | string | The prefix to the automatically generated widget IDs. Default: 'w'. | yii\ |
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$clientScript | array|yii\| | Client script class to use for client-side validation. Default: null. | ActiveForm |
$enableAjaxValidation | bool | Whether to enable AJAX-based data validation. Default: false. | ActiveForm |
$enableClientScript | bool | Whether to hook up yii.activeForm JavaScript plugin. Default: true. | ActiveForm |
$enableClientValidation | bool | Whether to enable client-side data validation. Default: true. | ActiveForm |
$encodeErrorSummary | bool | Whether to perform encoding on the error summary. Default: true. | ActiveForm |
$errorCssClass | string | The CSS class that is added to a field container when the associated attribute has validation error. Default: ''. | ActiveForm |
$errorSummaryCssClass | string | The default CSS class for the error summary container. Default: 'error-summary'. | ActiveForm |
$fieldClass | string | The default field class name when calling field() to create a new field. Default: 'yii\. | ActiveForm |
$fieldConfig | array|Closure | The default configuration used by field() when creating a new field object. Default: []. | ActiveForm |
$id | string | Id of the widget. | yii\ |
$method | string | The form submission method. Default: 'post'. | ActiveForm |
$options | array | The HTML attributes (name-value pairs) for the form tag. Default: []. | ActiveForm |
$requiredCssClass | string | The CSS class that is added to a field container when the associated attribute is required. Default: 'required'. | ActiveForm |
$scrollToError | bool | Whether to scroll to the first error after validation. Default: true. Available since 2.0.6. | ActiveForm |
$scrollToErrorOffset | int | Offset in pixels that should be added when scrolling to the first error. Default: 0. Available since 2.0.11. | ActiveForm |
$successCssClass | string | The CSS class that is added to a field container when the associated attribute is successfully validated. Default: ''. | ActiveForm |
$validateOnBlur | bool | Whether to perform validation when an input field loses focus. Default: true. | ActiveForm |
$validateOnChange | bool | Whether to perform validation when the value of an input field is changed. Default: true. | ActiveForm |
$validateOnSubmit | bool | Whether to perform validation when the form is submitted. Default: true. | ActiveForm |
$validateOnType | bool | Whether to perform validation while the user is typing in an input field. Default: false. | ActiveForm |
$validatingCssClass | string | The CSS class that is added to a field container when the associated attribute is being validated. Default: 'validating'. | ActiveForm |
$validationDelay | int | Number of milliseconds that the validation should be delayed when the user types in the field and $validateOnType is set true. Default: 500. | ActiveForm |
$validationStateOn | string | Where to render validation state class Could be either “container” or “input”. Default: self::VALIDATION_STATE_ON_CONTAINER. Available since 2.0.14. | ActiveForm |
$validationUrl | array| | The URL for performing AJAX-based validation. Default: null. | ActiveForm |
$view | yii\ | The view object that can be used to render views or view files. | yii\ |
$viewPath read-only | string | The directory containing the view files for this widget. | yii\ |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__clone() | This method is called after the object is created by cloning an existing one. | yii\ |
__get() | Returns the value of a component property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets the value of a component property. | yii\ |
__unset() | Sets a component property to be null. | yii\ |
afterRun() | This method is invoked right after a widget is executed. | yii\ |
attachBehavior() | Attaches a behavior to this component. | yii\ |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\ |
beforeRun() | This method is invoked right before the widget is executed. | yii\ |
begin() static | Begins a widget. | yii\ |
beginField() | Begins a form field. | ActiveForm |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\ |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
className() static | Returns the fully qualified name of this class. | yii\ |
detachBehavior() | Detaches a behavior from the component. | yii\ |
detachBehaviors() | Detaches all behaviors from the component. | yii\ |
end() static | Ends a widget. | yii\ |
endField() | Ends a form field. | ActiveForm |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\ |
errorSummary() | Generates a summary of the validation errors. | ActiveForm |
field() | Generates a form field. | ActiveForm |
getBehavior() | Returns the named behavior object. | yii\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
getId() | Returns the ID of the widget. | yii\ |
getView() | Returns the view object that can be used to render views or view files. | yii\ |
getViewPath() | Returns the directory containing the view files for this widget. | yii\ |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\ |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\ |
init() | Initializes the widget. | ActiveForm |
off() | Detaches an existing event handler from this component. | yii\ |
on() | Attaches an event handler to an event. | yii\ |
registerClientScript() | This registers the necessary JavaScript code. | ActiveForm |
render() | Renders a view. | yii\ |
renderFile() | Renders a view file. | yii\ |
run() | Runs the widget. | ActiveForm |
setId() | Sets the ID of the widget. | yii\ |
setView() | Sets the view object to be used by this widget. | yii\ |
trigger() | Triggers an event. | yii\ |
validate() static | Validates one or several models and returns an error message array indexed by the attribute IDs. | ActiveForm |
validateMultiple() static | Validates an array of model instances and returns an error message array indexed by the attribute IDs. | ActiveForm |
widget() static | Creates a widget instance and runs it. | yii\ |
getClientOptions() protected | ActiveForm |
Events
Section titled “Events”| Event | Type | Description | Defined by |
|---|---|---|---|
EVENT_INIT | yii\ | An event that is triggered when the widget is initialized via init(). Event name: 'init'. Available since 2.0.11. | yii\ |
EVENT_BEFORE_RUN | yii\ | An event raised right before executing a widget. Event name: 'beforeRun'. Available since 2.0.11. | yii\ |
EVENT_AFTER_RUN | yii\ | An event raised right after executing a widget. Event name: 'afterRun'. Available since 2.0.11. | yii\ |
Constants
Section titled “Constants”| Constant | Value | Description | Defined by |
|---|---|---|---|
VALIDATION_STATE_ON_CONTAINER | 'container' | Add validation state class to container tag Available since 2.0.14. | ActiveForm |
VALIDATION_STATE_ON_INPUT | 'input' | Add validation state class to input tag Available since 2.0.14. | ActiveForm |
Property details
Section titled “Property details”$action
Section titled “$action ”public array|string $action = ''The form action URL.
This parameter will be processed by Url::to().
$enableAjaxValidation
Section titled “$enableAjaxValidation ”public bool $enableAjaxValidation = falseWhether to enable AJAX-based data validation.
If ActiveField::$enableAjaxValidation is set, its value will take precedence for that input field.
$enableClientScript
Section titled “$enableClientScript ”public bool $enableClientScript = trueWhether to hook up yii.activeForm JavaScript plugin.
This property must be set true if you want to support client validation and/or AJAX validation, or if you
want to take advantage of the yii.activeForm plugin. When this is false, the form will not generate
any JavaScript.
$enableClientValidation
Section titled “$enableClientValidation ”public bool $enableClientValidation = trueWhether to enable client-side data validation.
If ActiveField::$enableClientValidation is set, its value will take precedence for that input field.
$fieldConfig
Section titled “$fieldConfig ”public array|Closure $fieldConfig = []The default configuration used by field() when creating a new field object.
This can be either a configuration array or an anonymous function returning a configuration array. If the latter, the signature should be as follows:
function ($model, $attribute)The value of this property will be merged recursively with the $options parameter passed to field().
$method
Section titled “$method ”public string $method = 'post'The form submission method.
This should be either post or get. Defaults to post.
When you set this to get you may see the url parameters repeated on each request.
This is because the default value of $action is set to be the current request url and each submit
will add new parameters instead of replacing existing ones.
You may set $action explicitly to avoid this:
$form = ActiveForm::begin([ 'method' => 'get', 'action' => ['controller/action'],]);$validateOnBlur
Section titled “$validateOnBlur ”public bool $validateOnBlur = trueWhether to perform validation when an input field loses focus.
If ActiveField::$validateOnBlur is set, its value will take precedence for that input field.
$validateOnChange
Section titled “$validateOnChange ”public bool $validateOnChange = trueWhether to perform validation when the value of an input field is changed.
If ActiveField::$validateOnChange is set, its value will take precedence for that input field.
$validateOnType
Section titled “$validateOnType ”public bool $validateOnType = falseWhether to perform validation while the user is typing in an input field.
If ActiveField::$validateOnType is set, its value will take precedence for that input field.
$validationDelay
Section titled “$validationDelay ”public int $validationDelay = 500Number of milliseconds that the validation should be delayed when the user types in the field and $validateOnType is set true.
If ActiveField::$validationDelay is set, its value will take precedence for that input field.
$validationStateOn
Section titled “$validationStateOn ”public string $validationStateOn = self::VALIDATION_STATE_ON_CONTAINERWhere to render validation state class Could be either “container” or “input”.
Default is “container”.
Since
2.0.14
$validationUrl
Section titled “$validationUrl ”public array|string|null $validationUrl = nullThe URL for performing AJAX-based validation.
This property will be processed by
Url::to(). Please refer to Url::to() for more details on how to configure this property.
If this property is not set, it will take the value of the form’s action attribute.
Method details
Section titled “Method details”beginField()
Section titled “beginField() ”public function beginField(yii\base\Model $model, string $attribute, array $options = []): stringBegins a form field.
This method will create a new form field and returns its opening tag.
You should call endField() afterwards.
Parameters
| Parameter | Type | Description |
|---|---|---|
$model | yii\ | The data model. |
$attribute | string | The attribute name or expression. See Html::getAttributeName() for the format about attribute expression. |
$options | array | The additional configurations for the field object. |
Returns
string: The opening tag.
See also
endField()
Section titled “endField() ”public function endField(): stringEnds a form field.
This method will return the closing tag of an active form field started by beginField().
Returns
string: The closing tag of the form field.
Throws
yii\base\InvalidCallException: if this method is called without a priorbeginField()call.
errorSummary()
Section titled “errorSummary() ”public function errorSummary(yii\base\Model|yii\base\Model[] $models, array $options = []): stringGenerates a summary of the validation errors.
If there is no validation error, an empty error summary markup will still be generated, but it will be hidden.
Parameters
| Parameter | Type | Description |
|---|---|---|
$models | yii\|yii\[] | The model(s) associated with this form. |
$options | array | The tag options in terms of name-value pairs. The following options are specially handled: - header: string, the header HTML for the error summary. If not set, a default prompt string will be used. - footer: string, the footer HTML for the error summary. The rest of the options will be rendered as the attributes of the container tag. The values will be HTML-encoded using Html::encode(). If a value is null, the corresponding attribute will not be rendered. |
Returns
string: The generated error summary.
See also
field()
Section titled “field() ”public function field(yii\base\Model $model, string $attribute, array $options = []): yii\widgets\ActiveFieldGenerates a form field.
A form field is associated with a model and an attribute. It contains a label, an input and an error message and use them to interact with end users to collect their inputs for the attribute.
Parameters
| Parameter | Type | Description |
|---|---|---|
$model | yii\ | The data model. |
$attribute | string | The attribute name or expression. See Html::getAttributeName() for the format about attribute expression. |
$options | array | The additional configurations for the field object. These are properties of ActiveField or a subclass, depending on the value of $fieldClass. |
Returns
ActiveField: The created ActiveField object.
See also
init()
Section titled “init() ”public function init(): mixedInitializes the widget.
This renders the form open tag.
Returns
mixed
registerClientScript()
Section titled “registerClientScript() ”public function registerClientScript(): mixedThis registers the necessary JavaScript code.
Returns
mixed
Since
2.0.12
run()
Section titled “run() ”public function run(): mixedRuns the widget.
This registers the necessary JavaScript code and renders the form open and close tags.
Returns
mixed
Throws
yii\base\InvalidCallException: ifbeginField()andendField()calls are not matching.
validate()
Section titled “validate() ”public static function validate(yii\base\Model $model, mixed $attributes = null): array<string, string[]>Validates one or several models and returns an error message array indexed by the attribute IDs.
This is a helper method that simplifies the way of writing AJAX validation code.
For example, you may use the following code in a controller action to respond to an AJAX validation request:
$model = new Post;$model->load(Yii::$app->request->post());if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validate($model);}// ... respond to non-AJAX request ...To validate multiple models, simply pass each model as a parameter to this method, like the following:
ActiveForm::validate($model1, $model2, ...);Parameters
| Parameter | Type | Description |
|---|---|---|
$model | yii\ | The model to be validated. |
$attributes | mixed | List of attributes that should be validated. If this parameter is empty, it means any attribute listed in the applicable validation rules should be validated. When this method is used to validate multiple models, this parameter will be interpreted as a model. |
Returns
array<string, string[]>: The error message array indexed by the attribute IDs.
validateMultiple()
Section titled “validateMultiple() ”public static function validateMultiple(array $models, mixed $attributes = null): arrayValidates an array of model instances and returns an error message array indexed by the attribute IDs.
This is a helper method that simplifies the way of writing AJAX validation code for tabular input.
For example, you may use the following code in a controller action to respond to an AJAX validation request:
// ... load $models ...if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validateMultiple($models);}// ... respond to non-AJAX request ...Parameters
| Parameter | Type | Description |
|---|---|---|
$models | array | An array of models to be validated. |
$attributes | mixed | List of attributes that should be validated. If this parameter is empty, it means any attribute listed in the applicable validation rules should be validated. |
Returns
array: The error message array indexed by the attribute IDs.
getClientOptions()
Section titled “getClientOptions() ”protected function getClientOptions(): mixedReturns
mixed