0

Assume that I have a page user create ,I want to multi create user on single views ,It mean that when submit form ,multi instances of model will be sent to controller to do saving, how can I accomplish it with Yii2 anything like this

public function actionMultiCreate() {
   if($request->isGet) {
      $user = new User()
      return $this->render("multi-create",['user' => $user]) 
   } else {
     //load array of user model and save it
   }
}

and views :

....
User1: <$form->field($model,'user-name')>
User2: <$form->field($model,'user-name')>
......

1 Answer 1

1

The simplest way is based on loadMultiple

public function actionCreate()
{
     if (Model::loadMultiple($items, Yii::$app->request->post()) && 
        Model::validateMultiple($items)) {
        $count = 0;
        foreach ($items as $item) {
           // populate and save records for each model
            $item->save()) 
        }
    }  
    ........

    .....
} 
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much ,I have another question ,how do I declare an array of model instance and send it to view?
In SO is fair post a single well defined question .. so if my answer is right please mark it as accepted and for the second questio please provide a proper well defined new post so all the community can help you
Thanks for your support

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.