Developing Yii2 form

Developing Yii2 form


Yii2 model with scenario


1. Creating multistep form with yii model scenario
- defining rules in model.

public function rules()
{
return [
[['name', 'email'], 'required', 'on' => 'step_one'],
[['sex','address','contact'], 'checkRoom', 'on' => 'step_two'],

[['middle_name'],'safe']
}


2. Creating model object with scenario in controller

$model = new Member(['scenario' => 'step_one']);
// submitting and validating form data
if ($request->isPost && $model->load(Yii::$app->request->post())) {
      if ($model->validate()) {
         
      }
}

3. Creating form in view file
- including helper,lib files,
- start and end form tags in yii2

use yii\bootstrap4\ActiveForm;

$form = ActiveForm::begin([
'id' => 'member-form-step-one',
'enableAjaxValidation' => false,
'enableClientValidation' => true,
]);

ActiveForm::end();


4. Form elements for yii model

- field option
> label(false)
> [{attributes}]

-  Hidden element

$form->field($model, 'name')->hiddenInput([
  'id' => 'name_id',
  "value" => 'defaultvalue',
 ])->label(false);

- Text element

echo $form->field($model, 'name')
->textInput([
'class'=>'form-control',
]);

- Dropdown / select element

$form->field($model, '')->dropDownList( $arrListOption,
[
     'prompt'=>'select..',
      'class'=>'select-room form-control select-option',
]);


- Checkbox list

$form->field($model, 'category')->checkboxList([ 1 => 'checkbox 1', 2 => 'checkbox 2' ]);

// with templating
$form->field($model, 'check_list')->checkboxList(listData() ,[ 'item' => function($index, $label, $name, $checked, $value) { $checked = $checked ? 'checked' : ''; return "
<div class='col-md-6 mb-2'>
<label class='form-check-label' >
<input class='form-check-input' type='checkbox' {$checked} name='{$name}' value='{$value}'>
{$label}</label>
</div>";
}]);

- Submit button

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










Share this

Related Posts

Previous
Next Post »