Yii2 how to setup form conditional validation for form input

Case:

You want to validate one form input based on the result of of the form.

In case I want to make comments to be necessary only if time is larger than 0. 

This can be achieved in the following way.

On Model add validation to public function rules()

[‘reply_time_comment’,’required’,
‘when’=>function ($model){
return $model->reply_timespent >0;
},
‘whenClient’=>”function (attribute, value) {
return $(‘#tickets-reply_timespent’).val() > ‘0’;
}”,’message’=>’Comment can\’t be empty when time is set’],
This is taken from your view while doing show source.
 
Name of form + attribute
tickets-reply_timespent
class=”input-group“>class=”input-group-addon“>Time:id=”tickets-reply_timespentclass=”form-controlname=”Tickets[reply_timespent]“>
 
 
then in your view row class are used so the form are inline instead one after another.
 
 
field($model, ‘reply_timespent’,[‘addon’=> [‘prepend’=> [‘content’=>’Time:’]]])->dropDownList(array_combine($addTimeFilter,$addTimeFilter))->label(false) ?>
 
 
field($model, ‘reply_time_comment’ ,[‘addon’=> [‘prepend’=> [‘content’=>’Time Comments:’]]])->textInput()->label(false) ?>
 
</div>