YII2: two models form validation, 2nd model requires dependency on the input of the first model

I am using YII2, advanced template, generating models with gii.

I created a form with two models ( A and B ), all validation rules are defined in the corresponding model, except for one rule, which is the best practice for the following cases.

in the shape of

model A . two input fields and one radio button CATEGORY ( YES or NO ). everyone demands

for fields Bed and . requires three input fields and

four additional input fields depend on the CATEGORY radio button , if the user is marked YES , which requires additional fields, and if marked NO , which does not require additional fields.

so how can I define a rule for client and server side validation? in which model? one of my solutions is to create a hybrid model and define all rules with dependency

+3


source to share


1 answer


I had the same problem and found this solution.

for example if your category attribute is in model A and if it was "yes" then the attribute of the element in model B must be specified.

for this example:

A.php model:

class A extends \yii\db\ActiveRecord
{
    public $category;

    public function rules()
    {
        return [
            [['category'], 'safe'],
        ];
    }



}

      



B.php class B extends \ yii \ db \ ActiveRecord

{
    public $item;
    public $category;

    public function rules()
    {
        return [
            [['item'], 'safe'],
            [['item'], 'required', 'when' => function($model) {
                return $model->category == 'yes';
            }]
        ];
    }       
}

      

and in the controller

$a = new A();
$b = new B();
if ($a->load(Yii::$app->request->post()) && $b->load(Yii::$app->request->post())) {
            $b->category= Yii::$app->request->post()['First']['category'];

            $isValid = $a->validate();
            $isValid = $b->validate() && $isValid;
            if ($isValid) {
                echo 'its valid';
            }


        }

      

0


source







All Articles