2017-02-21 54 views
0

我想在一個表中插入相同的記錄。我在下面的表格中只有一個輸入數組,但我想爲label input array保存多個時間記錄。 我的形式是插入同一張表的多條記錄Yii2

<div class="surveys-questions-form"> 

    <?php $form = ActiveForm::begin(); ?> 

    <?php 

     if(isset($_GET['option_id']) and $_GET['option_id'] > 0) 
      $id= $_GET['option_id']; 
     else 
      $id= $model->option_id; 
     echo $form->field($model, 'question_id')->hiddenInput(['value' => $id])->label(false); 
    ?> 

    <div class="col-md-6"> 
    <div id="question_wrapper"> 
     <?= $form->field($model, 'type')->dropDownList([ 'text' => 'Text', 'numbers' => 'Numbers', 'date' => 'Date', 'texarea' => 'Texarea', 'checkbox' => 'Checkbox', 'radio' => 'Radio', 'rating' => 'Rating', ], ['prompt' => '']) ?> 
     <div id="add_more_field"> 
      <?= $form->field($model, 'label[]')->textInput(['maxlength' => true]) ?> 
     </div> 
     <div class="form-group"> 
      <?php 
       echo Html::a('Add more', 'javascript:void(0);', [ 
        'id' => 'surveys-questions-new-button', 
        'class' => 'pull-right btn btn-primary btn-xs' 
       ]) 
      ?> 
     </div> 
    </div> 
    </div> 
    <div class="col-md-12"> 
    <div class="form-group"> 
     <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> 
    </div> 
    </div> 
    <?php ActiveForm::end(); ?> 

</div> 

和控制器

public function actionCreate() 
{ 
    $model = new QuestionsOptions(); 

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

給我下面的錯誤,當我嘗試提交表單。

Label must be a string. 

我的$ _POST陣列

Array 
(
    [_csrf-backend] => LXBhajI3YVpOIikeRWYHYkNCAD4Kb1ZrQzwER21GL2MdCTgkWm5ZDQ== 
    [QuestionsOptions] => Array 
     (
      [question_id] => 47 
      [type] => numbers 
      [label] => Array 
       (
        [0] => Label1 
        [1] => Label2 
        [2] => Labe3 
       ) 

     ) 

) 
+0

可以請你分享的print_r結果讓我對你發佈的數據有一些想法,然後我可以指導你 – Dani

+0

@Dani非常感謝。我已經修改了我的問題,你可以在後面的數組中看到 – Coder

回答

1

如果要保存多個記錄使用循環我建議你使用foreach循環最好是

public function actionCreate() 
{ 
     $model = new QuestionsOptions(); 

    if ($model->load(Yii::$app->request->post())) { 
      if(sizeof(array_filter($_POST['QuestionsOptions']['label'])) > 0){ 
      foreach($_POST['QuestionsOptions']['label'] as $key => $row){ 
        $model->setIsNewRecord(true); 
        $model->id = null; 
        $model->label = $row; 
        $model->save(); 
      } 
      } 
      return $this->redirect(['view', 'id' => $model->option_id]); 
     } else { 
      return $this->renderAjax('create', [ 
       'model' => $model, 
      ]); 
     } 
    } 
+0

@非常感謝你。但還有一件事,當我更新它們時我將如何處理。 – Coder

+0

我的意思是當我更新它們時,我如何顯示這些字段? – Coder

+0

你想在一個輸入字段中顯示??? – Dani