2016-11-25 3 views
0

양식에 2amigos SelectizeDropDownList 위젯을 구현하여 드롭 다운 내에서 직접 테이블에 새 값을 추가하려고합니다.2amigos를 사용하여 새 레코드 만들기 Yii2의 SelectizeDropDownList

모델 Book과 모델 작성자를 사용 중이므로 기본적으로 책 양식에 새 작성자를 추가 할 수 있기를 원합니다. 이 양식입니다

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; 
} 

양식 로드, 필터, 검색 및 새 항목 추가에 잘 작동합니다.

그러나 저자 테이블에 새로운 유형화 된 속성을 삽입하지 않습니다.

북 컨트롤러에 무엇인가를 추가해야합니까?

새로운 값인지 아니면 기존 작성자의 변경인지 어떻게 확인할 수 있습니까?

덕분에 많은

답변

0

내가 다음 코드와 함께 작동했다,하지 않도록하여 author_id는 숫자 나 문자열 인 경우 내가 확인하고 있기 때문에 가장 우아한. 필자의 경우 작성자는 숫자가 아닙니다.

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(), 
     ]); 
    } 
}