Skip to content
PHP Ecosystem
Explore

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.

PropertyTypeDescriptionDefined by
$actionarray|stringThe form action URL. Default: ''.ActiveForm
$ajaxDataTypestringThe type of data that you’re expecting back from the server. Default: 'json'.ActiveForm
$ajaxParamstringThe name of the GET parameter indicating the validation request is an AJAX request. Default: 'ajax'.ActiveForm
$autoIdPrefix staticstringThe prefix to the automatically generated widget IDs. Default: 'w'.yii\base\Widget
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$clientScriptarray|yii\web\client\ClientScriptInterface|nullClient script class to use for client-side validation. Default: null.ActiveForm
$enableAjaxValidationboolWhether to enable AJAX-based data validation. Default: false.ActiveForm
$enableClientScriptboolWhether to hook up yii.activeForm JavaScript plugin. Default: true.ActiveForm
$enableClientValidationboolWhether to enable client-side data validation. Default: true.ActiveForm
$encodeErrorSummaryboolWhether to perform encoding on the error summary. Default: true.ActiveForm
$errorCssClassstringThe CSS class that is added to a field container when the associated attribute has validation error. Default: ''.ActiveForm
$errorSummaryCssClassstringThe default CSS class for the error summary container. Default: 'error-summary'.ActiveForm
$fieldClassstringThe default field class name when calling field() to create a new field. Default: 'yii\widgets\ActiveField'.ActiveForm
$fieldConfigarray|ClosureThe default configuration used by field() when creating a new field object. Default: [].ActiveForm
$idstringId of the widget.yii\base\Widget
$methodstringThe form submission method. Default: 'post'.ActiveForm
$optionsarrayThe HTML attributes (name-value pairs) for the form tag. Default: [].ActiveForm
$requiredCssClassstringThe CSS class that is added to a field container when the associated attribute is required. Default: 'required'.ActiveForm
$scrollToErrorboolWhether to scroll to the first error after validation. Default: true. Available since 2.0.6.ActiveForm
$scrollToErrorOffsetintOffset in pixels that should be added when scrolling to the first error. Default: 0. Available since 2.0.11.ActiveForm
$successCssClassstringThe CSS class that is added to a field container when the associated attribute is successfully validated. Default: ''.ActiveForm
$validateOnBlurboolWhether to perform validation when an input field loses focus. Default: true.ActiveForm
$validateOnChangeboolWhether to perform validation when the value of an input field is changed. Default: true.ActiveForm
$validateOnSubmitboolWhether to perform validation when the form is submitted. Default: true.ActiveForm
$validateOnTypeboolWhether to perform validation while the user is typing in an input field. Default: false.ActiveForm
$validatingCssClassstringThe CSS class that is added to a field container when the associated attribute is being validated. Default: 'validating'.ActiveForm
$validationDelayintNumber of milliseconds that the validation should be delayed when the user types in the field and $validateOnType is set true. Default: 500.ActiveForm
$validationStateOnstringWhere to render validation state class Could be either “container” or “input”. Default: self::VALIDATION_STATE_ON_CONTAINER. Available since 2.0.14.ActiveForm
$validationUrlarray|string|nullThe URL for performing AJAX-based validation. Default: null.ActiveForm
$viewyii\web\ViewThe view object that can be used to render views or view files.yii\base\Widget
$viewPath read-onlystringThe directory containing the view files for this widget.yii\base\Widget
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.yii\base\Component
__clone()This method is called after the object is created by cloning an existing one.yii\base\Component
__get()Returns the value of a component property.yii\base\Component
__isset()Checks if a property is set, i.e. defined and not null.yii\base\Component
__set()Sets the value of a component property.yii\base\Component
__unset()Sets a component property to be null.yii\base\Component
afterRun()This method is invoked right after a widget is executed.yii\base\Widget
attachBehavior()Attaches a behavior to this component.yii\base\Component
attachBehaviors()Attaches a list of behaviors to the component.yii\base\Component
beforeRun()This method is invoked right before the widget is executed.yii\base\Widget
begin() staticBegins a widget.yii\base\Widget
beginField()Begins a form field.ActiveForm
behaviors()Returns a list of behaviors that this component should behave as.yii\base\Component
canGetProperty()Returns a value indicating whether a property can be read.yii\base\Component
canSetProperty()Returns a value indicating whether a property can be set.yii\base\Component
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
detachBehavior()Detaches a behavior from the component.yii\base\Component
detachBehaviors()Detaches all behaviors from the component.yii\base\Component
end() staticEnds a widget.yii\base\Widget
endField()Ends a form field.ActiveForm
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.yii\base\Component
errorSummary()Generates a summary of the validation errors.ActiveForm
field()Generates a form field.ActiveForm
getBehavior()Returns the named behavior object.yii\base\Component
getBehaviors()Returns all behaviors attached to this component.yii\base\Component
getId()Returns the ID of the widget.yii\base\Widget
getView()Returns the view object that can be used to render views or view files.yii\base\Widget
getViewPath()Returns the directory containing the view files for this widget.yii\base\Widget
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.yii\base\Component
hasMethod()Returns a value indicating whether a method is defined.yii\base\Component
hasProperty()Returns a value indicating whether a property is defined for this component.yii\base\Component
init()Initializes the widget.ActiveForm
off()Detaches an existing event handler from this component.yii\base\Component
on()Attaches an event handler to an event.yii\base\Component
registerClientScript()This registers the necessary JavaScript code.ActiveForm
render()Renders a view.yii\base\Widget
renderFile()Renders a view file.yii\base\Widget
run()Runs the widget.ActiveForm
setId()Sets the ID of the widget.yii\base\Widget
setView()Sets the view object to be used by this widget.yii\base\Widget
trigger()Triggers an event.yii\base\Component
validate() staticValidates one or several models and returns an error message array indexed by the attribute IDs.ActiveForm
validateMultiple() staticValidates an array of model instances and returns an error message array indexed by the attribute IDs.ActiveForm
widget() staticCreates a widget instance and runs it.yii\base\Widget
getClientOptions() protectedActiveForm
EventTypeDescriptionDefined by
EVENT_INITyii\base\EventAn event that is triggered when the widget is initialized via init(). Event name: 'init'. Available since 2.0.11.yii\base\Widget
EVENT_BEFORE_RUNyii\base\WidgetEventAn event raised right before executing a widget. Event name: 'beforeRun'. Available since 2.0.11.yii\base\Widget
EVENT_AFTER_RUNyii\base\WidgetEventAn event raised right after executing a widget. Event name: 'afterRun'. Available since 2.0.11.yii\base\Widget
ConstantValueDescriptionDefined 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
public array|string $action = ''

The form action URL.

This parameter will be processed by Url::to().

public bool $enableAjaxValidation = false

Whether to enable AJAX-based data validation.

If ActiveField::$enableAjaxValidation is set, its value will take precedence for that input field.

public bool $enableClientScript = true

Whether 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.

public bool $enableClientValidation = true

Whether to enable client-side data validation.

If ActiveField::$enableClientValidation is set, its value will take precedence for that input field.

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().

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'],
]);
public bool $validateOnBlur = true

Whether to perform validation when an input field loses focus.

If ActiveField::$validateOnBlur is set, its value will take precedence for that input field.

public bool $validateOnChange = true

Whether 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.

public bool $validateOnType = false

Whether 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.

public int $validationDelay = 500

Number 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.

public string $validationStateOn = self::VALIDATION_STATE_ON_CONTAINER

Where to render validation state class Could be either “container” or “input”.

Default is “container”.

Since

2.0.14

public array|string|null $validationUrl = null

The 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.

public function beginField(yii\base\Model $model, string $attribute, array $options = []): string

Begins a form field.

This method will create a new form field and returns its opening tag. You should call endField() afterwards.

Parameters

ParameterTypeDescription
$modelyii\base\ModelThe data model.
$attributestringThe attribute name or expression. See Html::getAttributeName() for the format about attribute expression.
$optionsarrayThe additional configurations for the field object.

Returns

string: The opening tag.

See also

public function endField(): string

Ends 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

public function errorSummary(yii\base\Model|yii\base\Model[] $models, array $options = []): string

Generates 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

ParameterTypeDescription
$modelsyii\base\Model|yii\base\Model[]The model(s) associated with this form.
$optionsarrayThe 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

public function field(yii\base\Model $model, string $attribute, array $options = []): yii\widgets\ActiveField

Generates 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

ParameterTypeDescription
$modelyii\base\ModelThe data model.
$attributestringThe attribute name or expression. See Html::getAttributeName() for the format about attribute expression.
$optionsarrayThe 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

public function init(): mixed

Initializes the widget.

This renders the form open tag.

Returns

mixed

public function registerClientScript(): mixed

This registers the necessary JavaScript code.

Returns

mixed

Since

2.0.12

public function run(): mixed

Runs the widget.

This registers the necessary JavaScript code and renders the form open and close tags.

Returns

mixed

Throws

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

ParameterTypeDescription
$modelyii\base\ModelThe model to be validated.
$attributesmixedList 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.

public static function validateMultiple(array $models, mixed $attributes = null): array

Validates 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

ParameterTypeDescription
$modelsarrayAn array of models to be validated.
$attributesmixedList 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.

protected function getClientOptions(): mixed

Returns

mixed