在yii2中以复选框形式验证

时间:2017-01-17 12:23:27

标签: php yii

我在表单中有两个模型。 一个模型是主模型,一个模型表示为连接表(模型)。

Relation

描述:

request_table : $model,
link_req_tipe : $modelLinkReqTipe;

我的目标是,

  1. 我保存了$ model,然后我得到了$ model-> id
  2. 我批量插入到link_req_item

    id_request = $ model-> id id_tipe = modelLinkReqTipe-> id_tipe

  3. 这是php:

    _form.php (仅举例,因为很多输入形式)

     <?= $form->field($model, 'karyawan_id')->dropDownList(
                    ArrayHelper::map(Karyawan::find()->all(), 'id', 'first_name'), ['prompt' => 'Select Karyawan'])
     ?>
    
    <?= $form->field($modelLinkReqTipe, 'id_tipe')->checkBoxList(ArrayHelper::map(TipeRequest::find()->all(), 'id', 'nama_tipe'));
     ?>
    

    RequestController

    if ($model->load($request->post()) && $modelLinkReqTipe->load(Yii::$app->request->post())) {
      $valid = $model->validate();
      $valid = $modelLinkReqTipe->validate() && $valid;  
    
      if ($valid) { ## Check validate : true
         $transaction = Yii::$app->db->beginTransaction();
         try {
           if ($flag = $model->save(false)) {
             foreach ($modelLinkReqTipe as $index => $modelLinkReqTipe ) {
                  if ($flag === false) {
                     break;
                  }
    
                  $modelLinkReqTipe->id_request = $model->id;
                  if (!($flag = $modelLinkReqTipe->save(false))) {
                      break;
                  }
             }
           }
    
           if ($flag) {
             $transaction->commit();
           } else {
             $transaction->rollBack()
           }
         }
         catch (\Exception $e) {
            $transaction->rollBack();
         }
    
         return [
           'forceReload' => '#crud-datatable-pjax',   
           'title' => "Create new Request",
           'content' => '<h1 class="text-success">Success</h1>,
           'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
                        Html::a('Create More', ['create'], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
                    ];
    
      }else{ ## Check validate : false
         return [
            'title' => "Create New Request",
            'content' => $this->renderAjax('create', [
                 'model' => $model,
                 'modelLinkReqTipe' => (empty($modelLinkReqTipe)) ? new LinkReqTipe() : $modelLinkReqTipe,
                 'modelLinkReqItem' => (empty($modelLinkReqItem)) ? [new LinkReqItem] : $modelLinkReqItem,
                        ]),
            'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
                        Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
                    ];
                }
    

    现在,验证遇到了麻烦, 它总是在提交时返回false。 false validation 请指教。

1 个答案:

答案 0 :(得分:1)

有很多方法可以解决此问题。我认为确保$modelLinkReqTipe属性id_request在验证时不考虑的最佳方法是为validate()函数提供您要验证的属性数组: validate(['id_tipe'])