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:
Only display the fields 'assigned_to' and 'phone' if the dropDownList selection for 'qualification_id' = 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);
?>