user3756758
user3756758

Reputation: 35

How do I validate multiple models with Yii?

I am using the following code to save and validate Booking and BookingRoom(link table) models, but I can only validate one at a time. I have had success in that the following saves and populates my database, but the validation occurs in sequence.

$Booking->save();

$BookingRoom->save();

How do I validate and save multiple models?

Upvotes: 3

Views: 1066

Answers (2)

Kunal Dethe
Kunal Dethe

Reputation: 1274

Explanation of $valid=$a->validate(); $valid=$b->validate() && $valid; -

  1. $valid=$a->validate(); will return TRUE or FALSE according to the validation.

    So lets say $valid=TRUE.

  2. Now when $valid=$b->validate() && $valid; is executed,

    the next model's validate is performed and some value is returned (TRUE OR FALSE).

  3. Statements will look like either $valid = TRUE && TRUE; or $valid = FALSE && TRUE;

So now the value of $valid in if($valid) { [...] }, is either TRUE or FALSE

and code will be executed accordingly.

Upvotes: 1

Everton Mendonça
Everton Mendonça

Reputation: 688

You should call the validate() method from the model, like the example bellow:

// populate input data to $a and $b
    $a->attributes=$_POST['A'];
    $b->attributes=$_POST['B'];

    // validate BOTH $a and $b
    $valid=$a->validate();
    $valid=$b->validate() && $valid;

    if($valid)
    {
        // use false parameter to disable validation
        $a->save(false);
        $b->save(false);
        // ...redirect to another page
    }

See this link for more information.

Upvotes: 2

Related Questions