Exemplo n.º 1
0
 /**
  * Updates an existing Book model.
  * If update is successful, the browser will be redirected to the 'view' page.
  *
  * @var Author[] $modelsAuthorNew
  * @param string $id Book id
  * @return mixed
  */
 public function actionUpdate($id)
 {
     $modelBook = $this->findModel($id);
     $modelBookForm = new BookForm($modelBook);
     $authorsId = $modelBook->getAuthors()->select('id')->asArray()->all();
     $modelsAuthor = Author::findAll($authorsId);
     //$modelBook->getAuthors()->asArray()->all();
     if ($modelBook->load(Yii::$app->request->post())) {
         $modelsAuthorNew = Model::createMultiple(Author::className());
         Model::loadMultiple($modelsAuthorNew, Yii::$app->request->post());
         //process, separate book keyWords
         $modelsKeyWordsNew = [new KeyWord()];
         if ($wordsArray = $modelBookForm->prepareKeyWords(Yii::$app->request->post('KeyWord')['words'])) {
             $modelsKeyWordsNew = Model::createMultiple(KeyWord::className(), [], $wordsArray);
             // KeyWord[0]['word' =>'php']
             Model::loadMultiple($modelsKeyWordsNew, $wordsArray, '');
         }
         $valid = $modelBook->validate();
         $valid = Model::validateMultiple($modelsAuthorNew) && $valid;
         $valid = $wordsArray === false ? $valid : Model::validateMultiple($modelsKeyWordsNew) && $valid;
         if ($valid && $modelBookForm->updateBook($modelsAuthor, $modelsAuthorNew, $modelsKeyWordsNew)) {
             Yii::$app->session->setFlash('success', Yii::t('app', Yii::t('app', 'Book was updated successfully.')));
             Yii::info($id . '_update', 'book');
             return $this->redirect(['view', 'id' => $modelBook->id]);
         } else {
             //get all errors from multiple models
             if (($msg = BookForm::getErrorsMessages($modelsAuthorNew)) !== false) {
                 Yii::$app->session->addFlash('danger', $msg);
             }
             if (($msg = BookForm::getErrorsMessages($modelsKeyWordsNew)) !== false) {
                 Yii::$app->session->addFlash('danger', $msg);
             }
         }
         Yii::$app->session->addFlash('danger', Yii::t('app', 'Book was not updated.'));
     }
     return $this->render('update', ['modelBook' => $modelBook, 'modelsAuthor' => empty($modelsAuthor) ? [new Author()] : $modelsAuthor, 'keyWords' => $modelBookForm->getKeyWords()]);
 }
Exemplo n.º 2
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getAuthors()
 {
     return $this->hasMany(Author::className(), ['id' => 'author_id'])->viaTable('book_author', ['book_id' => 'id']);
 }