Yii2 ActiveForm – Form Fields In Yii2

Showing Basic Example of the View Page in Yii2 For New Learners

These are basic classes you must to add to create form using yii2 ActiveForm

<?php

Use yii\helpers\Html;
Use yii\widgets\ActiveForm;

The Below line will start the form tag for our form below showing example shows that how to specify id for the form and how to apply any classes for the form..

$form =ActiveForm::begin([   'id'=> 'login-form',   'options'=> ['class' => 'form-horizontal'],]) ?>

Here $model Specify which database table field we want to bind with form that model object stored here in this variable which has been passed from the relevant controller.

   <?= $form->field($model, 'username') ?>
   <?= $form->field($model, 'password')->passwordInput() ?>

‘username’ and ‘password’ is the name of the table field with which our value will be bound.

Here in below code we are putting submit button for form submission and applying ‘Login’ as Button Text and basic css classes to it.

 <div class="form-group">
       <div class="col-lg-offset-1 col-lg-11">
           <?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
       </div>
   </div>

Here in below code we are Closing out form

<?php ActiveForm::end() ?>

Create Password Field :

<?= $form->field($model, 'password')->passwordInput() ?>

Create TextField :

<?= $form->field($model, 'username') ?>

Create Hidden Form Field :

echo $form->field($model, 'hidden1')->hiddenInput()->label(false);

Create Dropdown :

<?php echo $form->field($model, 'name')
->dropdownList(
Stud::find()->select(['name'])
->indexBy('name')->column(),
['prompt'=>'Select no']); ?>

Dropdown list with Id And Name

<?= $form->field($model, 'name')->dropDownList(
            ArrayHelper::map(Stud::find()->all(), 'no', 'name'),['prompt' => 'Select Car Name']
 ) ?>

Create FileUploader :

echo $form->field($model, 'imagepath')->fileInput();

Adding A Placeholder and Customized Label

 <?= $form->field($model, 'username')->textInput()->hint('Please enter your  name')->label('Name') ?>

if you want to reproduce, please indicate the source:
Yii2 ActiveForm – Form Fields In Yii2 - CodeDay