mootensai / yii2-enhanced-gii

Enhanced Yii2 Gii (generator) that generates related Models & CRUD
MIT License
203 stars 98 forks source link

How to validate related record without saving? #137

Open alvarolordelo opened 6 years ago

alvarolordelo commented 6 years ago

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 commented 6 years ago

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

alvarolordelo commented 6 years ago

@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 commented 6 years ago

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 commented 6 years ago

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!