Creating Forms ============== ActiveRecord based forms: ActiveForm ----------------------- The primary way of using forms in Yii is through [[yii\widgets\ActiveForm]]. This approach should be preferred when the form is based upon a model. Additionally, there are some useful methods in [[yii\helpers\Html]] that are typically used for adding buttons and help text to any form. A form, that is displayed on the client-side, will in most cases have a corresponding [model](structure-models.md) which is used to validate its input on the server-side (Check the [Validating Input](input-validation.md) section for more details on validation). When creating model-based forms, the first step is to define the model itself. The model can be either based upon an [Active Record](db-active-record.md) class, representing some data from the database, or a generic Model class (extending from [[yii\base\Model]]) to capture arbitrary input, for example a login form. > Tip: If the form fields are different from database columns or there are formatting and logic that is specific to that > form only, prefer creating a separate model extended from [[yii\base\Model]]. In the following example, we show how a generic model can be used for a login form: ```php 'login-form', 'options' => ['class' => 'form-horizontal'], ]) ?> field($model, 'username') ?> field($model, 'password')->passwordInput() ?>
'btn btn-primary']) ?>
``` ### Wrapping with `begin()` and `end()` In the above code, [[yii\widgets\ActiveForm::begin()|ActiveForm::begin()]] not only creates a form instance, but also marks the beginning of the form. All of the content placed between [[yii\widgets\ActiveForm::begin()|ActiveForm::begin()]] and [[yii\widgets\ActiveForm::end()|ActiveForm::end()]] will be wrapped within the HTML `
` tag. As with any widget, you can specify some options as to how the widget should be configured by passing an array to the `begin` method. In this case, an extra CSS class and identifying ID are passed to be used in the opening `` tag. For all available options, please refer to the API documentation of [[yii\widgets\ActiveForm]]. ### ActiveField In order to create a form element in the form, along with the element's label, and any applicable JavaScript validation, the [[yii\widgets\ActiveForm::field()|ActiveForm::field()]] method is called, which returns an instance of [[yii\widgets\ActiveField]]. When the result of this method is echoed directly, the result is a regular (text) input. To customize the output, you can chain additional methods of [[yii\widgets\ActiveField|ActiveField]] to this call: ```php // a password input field($model, 'password')->passwordInput() ?> // adding a hint and a customized label field($model, 'username')->textInput()->hint('Please enter your name')->label('Name') ?> // creating a HTML5 email input element field($model, 'email')->input('email') ?> ``` This will create all the `