M
M
Mick Coder2015-03-06 00:49:58
Yii
Mick Coder, 2015-03-06 00:49:58

Yii2AR. What is the correct way to create 50 models in the afterSave event of another model?

Hello! In AR, there are afterSave events that fire after the model record is saved. I need to generate approximately 50 records of another model in this event and store them in the corresponding table.

class Reservation extends \yii\db\ActiveRecord
public function afterSave($insert, $changedAttributes)
    {

      if (parent::afterSave($insert, $changedAttributes)) {
      	for ($i=0; $i < 50; $i++) {    
                   $modelRegCleanings = new RegularCleanings();
                   $modelRegCleanings->id_reservation = $this->id_reservation;
                   $modelRegCleanings->notes = $changedAttributes['notes'];
                   $modelRegCleanings->save();
               }
          return true;
      } else {
          return false;
      }
    }

The problem is that after saving 1 record of the Reservation model, a redirect to the view of the newly created record should occur
public function actionCreate()
    {
        $model = new Reservation();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
        	return $this->redirect(['view', 'id' => $model->id_reservation]);   
        } else {
        	return $this->render('create', [
        			'model' => $model,
        			]);
        }
    }

How to make it so that before the redirect a popup is displayed with notifications that when creating a given post, 50 posts of another model were created? And am I doing this generation in the right place? Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2015-03-06
@lbondodesc

I have no idea why you need to create 50 entries... oh my. Do where you want. True, for good, I would generally do it all in the service that would control this logic. Well, or would take out the generation in a static method of the target model ... everything depends on the business logic.
Concerning the notification - flash messages.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question