Yii2 - Show/Hide Fields on Form based on dropDown selection on form

1k views Asked by At

I am new to Yii2 and have been trying to work out how to hide/show certain fields on the form based on a dropDownList selection with client-side validation.

Basically I have a model and form view that collects information relating to 'candidates' and I wish to apply the following logic:

  1. Only display the fields 'assigned_to' and 'phone' if the dropDownList selection for 'qualification_id' = 2.

  2. The fields 'assigned_to' and 'phone' are required if 'qualification_id' = 2 (else optional)

My code is as follows, albeit not working as I need it to. The client-side validation is not working (i.e.'assigned_to' and 'phone' are not required when qualification_id = 2). I have not been able to work out how to hide/show the fields dynamically based on the 'qualification_id' selection. I assume some javascript is required for this.

Any assistance would be greatly appreciated!

MODEL:


namespace frontend\models;

use Yii;

/**
 * This is the model class for table "candidate".
 *
 * @property int $candidate_id
 * @property string $name
 * @property int $qualification_id
 * @property string $assigned_to
 * @property string $phone

    public static function tableName()
    {
        return 'candidate';
    }


    public function rules()
    {
        return [
            [['candidate_id', 'qualification_id', 'name'], 'required']
            [['candidate_id', 'qualification_id'], 'integer'],
            [['name', 'assigned_to’, 'phone’], 'string'],

            [['assigned_to', 'phone'],'required','when'=>function($model){
            
                return ($model->qualification_id == 2);
                },
                                    
            'whenClient'=>"function(attribute, value){
                    return $('#qualification_id').val() == 2; 
                                    
                 }"],

VIEW (form):


<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use frontend\models\QualificationType;

/* @var $this yii\web\View */
/* @var $model frontend\models\Candidate */
/* @var $form yii\widgets\ActiveForm */

?>


<div class="candidate-form">

    <?php $form = ActiveForm::begin(); ?>


    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>


    <?= $form->field($model, 'qualification_id')->dropDownList(
        ArrayHelper::map(QualificationType::find()->all(),'qualification_id','qualification'),
        [
        'prompt'=>'Select...',
        'id' => 'review_type_id', 
        'onchange' => 'changeQualification()'
]
    ) ?>

    <?= $form->field($model, 'assigned_to')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'phone')->textInput(['maxlength' => true]) ?>

    <div class="form-group">
        <?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
    
    </div>

    <?php ActiveForm::end(); ?>

</div>

<?php

    $script = <<<JS
    function changeQualification() {
      if ($('#qualification_id').val() == 2) {
       $('#assigned_to').show();
       $('#name).show();

      } else {

       $('#assigned_to).hide();
       $('#name).hide();
      }
    }
    JS;

    $this->registerJs($script);

    ?>

1

There are 1 answers

17
SmartMan21Cen On

Please try like this

In view

<div class="candidate-form">
        <?php $form = ActiveForm::begin(); ?>
        <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
        <?= $form->field($model, 'qualification_id')->dropDownList(
            ArrayHelper::map(QualificationType::find()->all(),'qualification_id','qualification'),
            ['prompt'=>'Select...', 'id' => 'qualification_id', 'onchange' => 'changeQualificationType()']
        ) ?>
    
        <?= $form->field($model, 'assigned_to)->textInput(['id' => 'assigned_to_Input', 'maxlength' => true]) ?>
    
        <?= $form->field($model, 'phone')->textInput(['id' => 'phone_input', 'maxlength' => true]) ?>
    
        <div class="form-group">
            <?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
        
        </div>
    
        <?php ActiveForm::end(); ?>
    
    </div>



<?php
$script = <<<JS
    function changeQualificationType() {
      if ($('#qualification_id').val() == 2) {
       $('#assigned_to_input').closest('.form-group').show();
       $('#phone_input').closest('.form-group').show();
      } else {
       $('#assigned_to_input').closest('.form-group').hide();
       $('#phone_input').closest('.form-group').hide();
      }
    }
JS;
$this->registerJs($script);

In Model

public function rules()
    {
        return [
            [['candidate_id', 'qualification_id', 'name'], 'required']
            [['candidate_id', 'qualification_id'], 'integer'],
            [['name', 'assignedTo, 'phone’], 'string'],

            [['assignedTo', 'phone'],'required','when'=>function($model){
            
                return ($model->qualification_id == 2);
                },
                                    
            'whenClient'=>"function(attribute, value){
                    return $('#qualification_id').val() == 2; 
                                    
                 }"],

Don't forget to set custom id in ActiveFormField. All of field id should be matched with functions of Jquery and Model.