This article will explain the better way to use Form Input Fields in Yii2.0. Folder structure of ‘yii\widgets\ActiveForm’ class is used to create a form and ‘yii\helpers\Html’ class is used to display the different type of HTML input fields like buttons, textbox, checkbox, radio buttons, select box etc.
Start nad end the active Form
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php use yii\helpers\Html; use yii\widgets\ActiveForm; //$form = ActiveForm::begin(); //Default Active Form begin $form = ActiveForm::begin([ 'id' => 'active-form', 'options' => [ 'class' => 'form-horizontal', 'enctype' => 'multipart/form-data' ], ]) /* ADD FORM FIELDS */ ActiveForm::end(); ?> |
Imput field Text box
1 2 3 4 | //Format 1 <?= $form->field($model,'name'); ?> //Format 2 <?= $form->field($model, 'name')->textInput()->hint('Please enter your name')->label('Name') ?> |
Input field Text Area
1 2 3 | <?php $form->field($model, 'desc')->textarea(); ?> <?php $form->field($model, 'desc')->textarea()->label('Description'); ?> <?php $form->field($model, 'desc')->textarea(array('rows'=>2,'cols'=>5)); ?> |
HTML5 input fields Email and password
Password input field.
1 2 3 4 5 6 | //Example 1 <?php $form->field($model, 'password')->input('password') ?> //Example 2 <?php $form->field($model, 'password')->passwordInput() ?> //Example 3 <?php $form->field($model, 'password')->passwordInput()->hint('Password should be within A-Za-z0-9')->label('Password Hint') ?> |
HTML5 input field.
1 | <?php $form->field($model, 'email')->input('email') ?> |
DropDown List Input Field
dropDownList() fuction create the select html tags.
1 2 3 4 | //Exapmle 1 <?php echo $form->field($model, 'name')->dropDownList(['a' => 'Item A', 'b' => 'Item B', 'c' => 'Item C']); ?> //Exapmle 2 <?php echo $form->field($model, 'name')->dropDownList($listData, ['prompt'=>'Choose...']);> |
File Upload Input field
1 2 3 4 5 6 | Single file upload <?php $form->field($model, 'uploadFile')->fileInput() ?> Multiple file uploads <?php echo $form->field($model, 'uploadFile[]')->fileInput(['multiple'=>'multiple']); ?> |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: Php Framework, Tip and tricks, Tutorials, Yii