I am using username field in form,i set rule like below.
['username', 'required','when' => function($model) {
return $model->pin == true;
}],
(i.e)when the property pin goes true that time only i need username field required,all are working fine in clientside,but this validation falis on serverside,what is wrong on my code.
UPDATE:
controller code
public function actionTest()
{
$model = new Test();
if ($model->load(Yii::$app->request->post()) && $model->customValidation()) {
if($model->validate())
{
//
}
}
return $this->render('testView', [
'model' => $model,
]);
}
model
public $username;
public $pin = false;
public function rules()
{
return [
['username', 'required','message' => 'You must enter username','when' => function($model) {
return $model->pin == true;
}],
];
}
public function customValidation()
{
if()
{
$this->pin = true;
return false;
}
else
{
return true;
}
}
view
if($model->pin)
{
<?= $form->field($model, 'username')->textInput(); ?>
}
You need to add
whenClient
for this to work on the client side:where JS condition depends on the DOM structure you have got. For example if pin property is checkboxed with id
pin
this can be:UPDATE:
If you just set
pin
property in model you can modify the validation rule like that: