Yii Framework 2 : ActiveForm Input Fields

'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, select box etc.
ActiveForm::begin() - creates a form instance and  beginning of the form.
ActiveForm::begin() and ActiveForm::end() - All of the content placed between this.

Use the namespace For ActiveForm


<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
'ActiveForm' namespace is very important to create the a active form and 'Html' namespace is very useful to display the different html input fields.

Active Form Begin And End


<?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();
?>
Here we added active form with basic details like form id, class and enctype for file uploads.

Text Input Field


//Format 1
<?= $form->field($model,'name'); ?>
//Format 2
<?= $form->field($model, 'name')->textInput()
                    ->hint('Please enter your name')
                    ->label('Name') ?>
	
Format 1 is a normal text input field. Format 2 is a text input field with hint, label.

TextArea Field

The model attribute value will be used as the content in the textarea.

<?= $form->field($model, 'desc')->textarea(); ?>
<?= $form->field($model, 'desc')->textarea()
                    ->label('Description'); ?>
<?= $form->field($model, 'desc')->textarea(array('rows'=>2,'cols'=>5)); ?>
	

Password Input Field


//Format 1
<?= $form->field($model, 'password')->input('password') ?>
//Format 2
<?= $form->field($model, 'password')->passwordInput() ?>
//Format 3
<?= $form->field($model, 'password')->passwordInput()
                    ->hint('Password should be within A-Za-z0-9')
                    ->label('Password Hint') ?>
	
We added different type of password input field like password with hint, custom lable.

HTML5 Email Input Field


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

File Upload

fileInput() function is used to create a file input fields and 'multiple' parameter is used to upload multiple file in single upload.
Single File Upload

<?= $form->field($model, 'uploadFile')->fileInput() ?>
	
MultiFile Upload

<?php echo $form->field($model, 'uploadFile[]')
                    ->fileInput(['multiple'=>'multiple']); ?>
	

Checkbox Button Field

Using below we can create the Checkbox base on model attribute of yii2.0 framework. We added the following options like custom label, disabled, style etc

<!-- CHECKBOX BUTTON DEFAULT LABEL -->
<?= $form->field($model, 'population')->checkbox(); ?>
<!-- CHECKBOX BUTTON WITHOUT LABEL -->
<?= $form->field($model, 'population')->checkbox(array('label'=>'')); ?>
<!-- CHECKBOX BUTTON WITH CUSTOM LABEL -->
<?= $form->field($model, 'population')->checkbox(array('label'=>''))
			->label('Gender'); ?>
<!-- CHECKBOX BUTTON WITH LABEL OPTIONS, DISABLED AND STYLE PROPERTIES -->
<?= $form->field($model, 'population')->checkbox(array(
					'label'=>'',
					'labelOptions'=>array('style'=>'padding:5px;'),
					'disabled'=>true
					))
					->label('Gender'); ?>

	

Checkbox List Input Field

checkboxList() function is used to display the check box list using array of input argument values.

<?php echo $form->field($model, 'name[]')->checkboxList(
			['a' => 'Item A', 'b' => 'Item B', 'c' => 'Item C']
   );
?>
	

Radio Button Field

The model attribute value will be used to create the redio button.

<!-- RADIO BUTTON DEFAULT LABEL -->
<?= $form->field($model, 'gender')->radio(); ?>
<!-- RADIO BUTTON WITHOUT LABEL -->
<?= $form->field($model, 'gender')->radio(array('label'=>'')); ?>
<!-- RADIO BUTTON WITH CUSTOM LABEL -->
<?= $form->field($model, 'gender')->radio(array('label'=>''))
			->label('Gender'); ?>
<!-- RADIO BUTTON WITH LABEL OPTIONS -->
<?= $form->field($model, 'gender')->radio(array(
			'label'=>'',
			'labelOptions'=>array('style'=>'padding:5px;')))
			->label('Gender');
?>
	

Radio Button List Field

The model attribute value will be used to create the redio button list.

<?= $form->field($model, 'population')->radioList(array('1'=>'One',2=>'Two')); ?>
	

ListBox Field

Using below we can create the list box base on model attribute of yii2.0 framework. We added the following options like prompt, size, disabled, style etc

<!-- Listbox with prompt text -->
<?= $form->field($model, 'population')->listBox(
			array('1'=>'1',2=>'2',3=>3,4=>4,5=>5),
			array('prompt'=>'Select')
			);
?>
<!-- Listbox with size -->
<?= $form->field($model, 'population')->listBox(
			array('1'=>'1',2=>'2',3=>3,4=>4,5=>5),
			array('prompt'=>'Select','size'=>3)
			);
?>
<!-- Listbox with disabled, style properties -->
<?= $form->field($model, 'population')->listBox(
			array('1'=>'1',2=>'2',3=>3,4=>4,5=>5),
			array(
			    'disabled' => true,
			    'style'=>'background:gray;color:#fff;')
			)
			->label('Gender');
?>
	
dropDownList() function is used to create HTML 'select' tag input field.

//Format 1
<?php echo $form->field($model, 'name')->dropDownList(
			['a' => 'Item A', 'b' => 'Item B', 'c' => 'Item C']
			); ?>
// Format 2
<?php echo $form->field($model, 'name')->dropDownList(
			$listData, 
			['prompt'=>'Choose...']
			); ?>
	

Submit Button


<?= Html::submitButton('Submit', ['class'=> 'btn btn-primary']); ?>
	

  • Luis M

    Hi guys, i need input calendar for yii2 any example??

    • Jose Manuel Kun

      ” $form->field($model, ‘name’)->input(‘date’) “

      • moses egboh

        Hello,the code works in the view but does not insert into the database because of the format, please how can I format the date so that it is acceptable in mysql database?

  • Ramanand

    Very Nice…..

  • mj tappy

    hi guyz.. i have a questions its related in the topic above.. lets say i have a column children so in the view it should be like $form->field($model, ‘children’)->textInput([‘maxLenght’=>30]) add want to add a button, that button will be adding additiona field for children after that all children input will be save in one row in db using implode… how to do that guyz.. need help.

    • m bala

      Add below code

      $form->field($model, ‘children[]’)->textInput([‘maxLenght’=>30])

      To add the additional field, you have to write code in jQuery

      • mj tappy

        what about if in the update part? how should i explode that array? I can explode it using normal textinput the problem is using the yii form..

  • L_program

    Hi guys, i need input datetime for yi2 any example?

  • Ovi

    How to set default value in radio list please help…

  • Great post. Thanks.

  • Thank you.

  • shustr8

    How do you make Item B, or Item C selected in dropdownlist?

  • Giovanny Franco Herrera

    How to set disabled radio list when I try update ?

  • Amirtha Suresh

    how to add a clipboard in atext box in yii2.please help me with an example

  • ravi

    greate

  • Rosalia A. Matuz

    Graciaas! Me ayudo mucho tu post (:

  • Avinash Raut

    very useful thanks!

  • Jose Manuel Kun

    For input calendar “date picker” you only should do this:
    ” $form->field($model, ‘name’)->input(‘date’) ”
    it works on yii2, i don’t know if it’s the same in yii1…

    • moses egboh

      Hello,the code works properly in the view but does not insert into the database because of the format, please how can I format the date so that it is acceptable in mysql database?

      • Jose Manuel Kun

        May be you need to implement DataTransformation, I used it in my model, something like this:
        so you will use “dateCreationDT” instead of “dateCreation”.

        public function rules() {
        return [
        // # DateCreation (Data Transformation) rules
        [['dateCreationDT'], 'required'],
        }

        ... ... ...

        public function getDateCreationDT() {
        if ($this->dateCreation != '') {
        return date('d-m-Y', strtotime($this->dateCreation));
        }
        }

        public function setDateCreationDT($value) {
        $this->dateCreation = Date('Y-m-d', strtotime($value));
        }

        db-active-record: Data Transformation

        • moses egboh

          Hello thanks for your prompt response.much appreciated.I understand this code goes to the model. But how will I use it in the view.Will I use it the normal way: example: field($model, ‘end_date’)->input(‘date’); ?>

          • Jose Manuel Kun

            You’re welcome, ok, you have to use the data transformation attribute:

            field($model, ‘dateCreationDT’)->input(‘date’); ?>

            Yii will use your data transformation attribute as any other attribute of your model, check it out in the documentation: https://www.yiiframework.com/doc/guide/2.0/en/db-active-record

  • Jane

    how can i checkbox to be checked based on the value in the database .if the status is 1 then the checkbox to be checked

  • Azamat

    When I use siimple form, it gives me the following error please Help,
    yiibaseErrorException: Object of class yiiwidgetsActiveForm could not be converted to string in C:xampphtdocsfinaledocsfrontendviewsdocumentsview.php:22