2017-02-23 63 views
0

我想用jquery創建動態字段而不使用任何庫。我有兩個提交表格,但其中一個提交label我想創建多個時間,這實際上是問題選項,它可以是更多的一次。如何更新yii2中的動態字段

在下面的form.php中,你會看到我用多個時間創建jQuery的label field。我可以拯救他們,但我不明白我將如何顯示那些在update case以上的時間。真的很抱歉我的英語。

控制器

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->option_id = null; 
        $model->label = $row; 
        $model->save(); 
      } 
      } 
     // exit; 
      return $this->redirect(['view', 'id' => $model->option_id]); 
     } else { 
      return $this->renderAjax('create', [ 
       'model' => $model, 
      ]); 
     } 
    } 

型號

namespace app\models; 
use Yii; 

class QuestionsOptions extends \yii\db\ActiveRecord 
{ 
    public static function tableName() 
    { 
     return 'questions_options'; 
    } 
    public function rules() 
    { 
     return [ 
      [['question_id', 'label', 'type'], 'required'], 
      [['question_id'], 'integer'], 
      [['type'], 'string'], 
      [['dated', 'updated'], 'safe'], 
      [['label'], 'string', 'max' => 255], 
      [['question_id'], 'exist', 'skipOnError' => true, 'targetClass' => SurveysQuestions::className(), 'targetAttribute' => ['question_id' => 'question_id']], 
     ]; 
    } 
    public function attributeLabels() 
    { 
     return [ 
      'option_id' => 'Option ID', 
      'question_id' => 'Question ID', 
      'label' => 'Label', 
      'type' => 'Type', 
      'dated' => 'Dated', 
      'updated' => 'Updated', 
     ]; 
    } 
    public function getQuestionsAnswers() 
    { 
     return $this->hasMany(QuestionsAnswers::className(), ['option_id' => 'option_id']); 
    } 
    public function getQuestion() 
    { 
     return $this->hasOne(SurveysQuestions::className(), ['question_id' => 'question_id']); 
    } 
} 

form.php的

<?php 

use yii\helpers\Html; 
use yii\widgets\ActiveForm; 

?> 

<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> 
<?php 
$script = <<< JS 
$(document).ready(function(){ 

    $('#surveys-questions-new-button').on('click', function() { 
     $("#add_more_field").clone().appendTo("#question_wrapper"); 
    }); 

}); 

JS; 
$this->registerJs($script); 
?> 

也許其他東西也是不對的在我的代碼,請可以建議我,我真的很需要幫助。

+0

我可以建議你一些事情,但在此之後,你的驗證將無法正常工作.... – Dani

回答

0

我有幾點意見,以改善和返工代碼:

  1. 創建QuestionOptionsForm可能加載動態添加選項/標籤。使用此模型迭代選項(可以從請求或數據庫中加載)。不要使用像$_GET['option_id']這樣的語句(特別是在視圖中)。

  2. 在窗體上添加新選項(動態)時,爲字段名稱添加integer-index。例如label[45]。我通常使用特殊的html模板替換。用這種方法代替現有行的克隆。例如:

    <div class="js-new-option-template"> 
        <input type="text" name="option[{{OPTION_ID}}][label]"/> 
        <input type="hidden" name="option[{{OPTION_ID}}][is_new_option]"/> 
    </div> 
    

    注:你需要從一個JS代碼產生的動態分離現有選項ID。您可以使用is_new_option隱藏字段。

  3. 當您還原現有選項時,請使用它們的ID將它們編入索引。

  4. 然後,當您迭代選項時,爲現有選項加載模型,併爲動態生成的模型創建新模型。

    // ... 
    foreach ($modelForm->options as $optionId => $optionData) { 
    
        // Prepare data 
        $isNewModel  = \yii\helpers\ArrayHelper::getValue($optionData, 'is_new_option', true); 
        $optionLabel = \yii\helpers\ArrayHelper::getValue($optionData, 'label'); 
        $optionQuestion = \yii\helpers\ArrayHelper::getValue($optionData, 'question_id'); 
    
        // Create or find options model 
        $modelOption = $isNewModel 
         ? new QuestionsOptions() 
         : QuestionsOptions::findOne($optionId); 
    
        if (!$modelOption) { 
         throw new \yii\web\NotFoundHttpException('Cannot be found option record with the id = ' . $optionId); 
        } 
    
        // Populate and save model 
        $modelOption->label  = $optionLabel; 
        $modelOption->question_id = $optionQuestion; // foreign key 
    
        if (!$modelOption->save()) { 
         throw new \yii\base\Exception('Cannot be saved new option record.'); 
        } 
    } 
    
  5. 如有必要,您可以刪除表單上已刪除的數據庫選項。

+0

謝謝@ IStranger。我沒有得到它$ modelOption = $ isNewModel?新的QuestionsOptions():QuestionsOptions :: findOne($ optionId); – Coder

+0

還有一件事,如果你把js代碼,它會更好。當你獲得時間 – Coder