2016-11-25 2 views
0

2amigos SelectizeDropDownListウィジェットをフォームに実装して、ドロップダウン内のテーブルに新しい値を直接追加しようとしています。2amigosを使って新しいレコードを作成するYii2のSelectizeDropDownList

私はBookモデルとModel Authorモデルを使用していますので、基本的にブックフォームに新しい著者を追加したいと考えています。

これは、更新機能でのブックコントローラです:

public function actionUpdate($id) { 
    $model = $this->findModel($id); 

    if ($model->load(Yii::$app->request->post()) && $model->save()) { 
     return $this->redirect(['index']); 
    } else { 
     return $this->render('update', [ 
        'model' => $model, 
        'categories' => BookCategory::find()->active()->all(), 
        'publishers' => Publisher::find()->all(), 
        'copirights' => Copiright::find()->all(), 
        'authors' => Author::find()->all(), 
     ]); 
    } 
} 

これは形式です:

 <?= 
     $form->field($model, 'author_id')->widget(SelectizeDropDownList::className(), [ 
      // calls an action that returns a JSON object with matched 
      // tags 
      'loadUrl' => ['author/list'], 
      'value' => $authors, 
      'items' => \yii\helpers\ArrayHelper::map(\common\models\author::find()->orderBy('name')->asArray()->all(), 'id', 'name'), 
      'options' => [ 
       'class' => 'form-control', 
       'id' => 'id' 
      ], 
      'clientOptions' => [ 
       'valueField' => 'id', 
       'labelField' => 'name', 
       'searchField' => ['name'], 
       'autosearch' => ['on'], 
       'create' => true, 
       'maxItems' => 1, 
      ], 
     ]) 
     ?>  

そして、これは機能の作者コントローラです:

public function actionList($query) { 
    $models = Author::findAllByName($query); 
    $items = []; 

    foreach ($models as $model) { 
     $items[] = ['id' => $model->id, 'name' => $model->name]; 
    } 

    Yii::$app->response->format = \Yii::$app->response->format = 'json'; 

    return $items; 
} 

フォームフィルター、検索、新しい項目の追加には問題ありません。

ただし、新しい型付き属性は、authorテーブルに挿入されません。

ブックコントローラに何かを追加する必要がありますか?

新しい値か既存の著者の変更であるかどうかを確認するにはどうすればよいですか?私はAUTHOR_IDが数値または文字列である場合、私はチェックしていますので、それは次のコードではなく、必ず最もエレガントで働かせた

どうもありがとう

答えて

0

。 私の場合、作者はとにかく数字ではありません。

public function actionUpdate($id) { 
    $model = $this->findModel($id); 

    if ($model->load(Yii::$app->request->post())) { 
     $x = Yii::$app->request->post('Book'); 
     $new_author = $x['author_id']; 
     if (!is_numeric($new_author)) { 
      $author = new Author(); 
      $author->name = $new_author; 
      $author->save(); 
      $model->author_id = $author->id; 
     } 
     if ($model->save()) { 
      return $this->redirect(['index']); 
     } 
    } else { 
     return $this->render('update', [ 
        'model' => $model, 
        'categories' => BookCategory::find()->active()->all(), 
        'publishers' => Publisher::find()->all(), 
        'copirights' => Copiright::find()->all(), 
        'authors' => Author::find()->all(), 
     ]); 
    } 
} 
関連する問題