Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to validate related record without saving? #137

Open
alvarolordelo opened this issue Feb 26, 2018 · 4 comments
Open

How to validate related record without saving? #137

alvarolordelo opened this issue Feb 26, 2018 · 4 comments

Comments

@alvarolordelo
Copy link

Using the main structure we have
if ($model->loadAll(Yii::$app->request->post()) && $model->saveAll()) {
but to me I should first validate all the related records do some stuff and then saveAll()
is there any way to validate related records without saving ?

@cgernert
Copy link
Contributor

if ($model->loadAll(Yii::$app->request->post())) {
// do some stuff with the model
$model->saveAll(['taskEvents']);
}

@alvarolordelo
Copy link
Author

@cgernert I may not be clear enough, thus I will explain better.
In my case I do need to validate related records as well,
$model is validated and $model->related records should be validated,
in my case I'm using the dynamic form to send model and model related record(s).
what I want is to validate all ...the model and the model related record(s) ...before saving it...
Example:
if ($model->loadAll(Yii::$app->request->post()) && $model->validateAll() ) {
//do some stuff

$model->saveAll();
Now I think you may be got what I need ...

@cgernert
Copy link
Contributor

cgernert commented Mar 1, 2018

With loadAll() you already loaded them from POST. But I am afraid you have to iterate the rel. entity manually :

if ($model->loadAll(Yii::$app->request->post())) { 
  foreach ($model->getRelatedRecords() as $relEntity) { 
    foreach ($relEntity as $record) { 
      if ($record->validate()) { 
        //everything's ok 
      } else { 
        // do stuff 
      }
    } 
  } 
  $model->saveAll();
}

You do not have to iterate all $model->getRelatedRecords() if you have a $model->specificThings in mind and get rid of the outer foreach loop.

@alvarolordelo
Copy link
Author

Thanks for your help! I appreciated a lot, though a method like validateAll() would be more convenient for all scenarios.
I hope my question may help others in the future.
Have a nice time!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants