2017-09-07 10 views
0

yii2의 송장을 작성하고 새로운 문제가 발생했습니다. 당신이 양식을 작성하고 생성을 클릭하면 페이지를 새로 고치고 제품 필드를 지우는 것을 제외하고는 아무 것도하지 않습니다. 그러나 회사 이름과 날짜와 같은 개인 정보는 새로 고침 후에도 채워집니다. 데이타베이스는 아무 일도 일어나지 않았다. 아래의 코드를 살펴 보시기 바랍니다.YII2 create 함수가 데이터베이스에 데이터를 보내지 않습니다. 내 마지막 질문 후

내가이 양식 작동하기 때문에 문제가 아니었지만, 여전히 편리 할 수도 있습니다 생각 청구서 양식

<?php 

use yii\helpers\Html; 
use yii\widgets\ActiveForm; 
use wbraganca\dynamicform\DynamicFormWidget; 
use kartik\datecontrol\Module; 
use kartik\datecontrol\DateControl; 
use kartik\select2\Select2; 
use yii\helpers\ArrayHelper; 
use app\models\Companies; 
use app\models\Spokepersons; 



/* @var $this yii\web\View */ 
/* @var $model app\models\Facturen */ 
/* @var $form yii\widgets\ActiveForm */ 
?> 

<div class="facturen-form"> 

    <?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?> 

    <?= $form->field($model, 'company_name')->widget(Select2::classname(), [ 
    'data' => ArrayHelper::map(Companies::find()->all(), 'company_id', 'company_name'), 
    'language' => 'nl', 
    'options' => ['placeholder' => 'Selecteer een bedrijf'], 
    'pluginOptions' => [ 
     'allowClear' => true 
    ], 
])?> 

    <?= $form->field($model, 'spokes_person')->widget(Select2::classname(), [ 
    'data' => ArrayHelper::map(Spokepersons::find()->all(), 'person_id', 'first_name'), 
    'language' => 'nl', 
    'options' => ['placeholder' => 'Selecteer een contactpersoon'], 
    'pluginOptions' => [ 
     'allowClear' => true 
    ], 
])?> 

    <?= $form->field($model, 'date')->widget(DateControl::classname(), [ 
    'type' => 'date', 
    'ajaxConversion' => true, 
    'autoWidget' => true, 
    'widgetClass' => '', 
    'displayFormat' => 'php:d-F-Y', 
    'saveFormat' => 'php:Y-m-d', 
    'saveTimezone' => 'UTC', 
    'displayTimezone' => 'Europe/Amsterdam', 
    'saveOptions' => [ 
     //'label' => 'Input saved as: ', 
     // 'type' => 'text', 
     'readonly' => true, 
     'class' => 'hint-input text-muted' 
    ], 
    'widgetOptions' => [ 
     'pluginOptions' => [ 
      'autoclose' => true, 
      'format' => 'php:d-F-Y' 
     ] 
    ], 
    'language' => 'nl' 
]) ?> 

    <div class="row"> 
     <div class="panel-body"> 
      <?php DynamicFormWidget::begin([ 
       'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_] 
       'widgetBody' => '.container-items', // required: css class selector 
       'widgetItem' => '.item', // required: css class 
       'limit' => 999, // the maximum times, an element can be cloned (default 999) 
       'min' => 1, // 0 or 1 (default 1) 
       'insertButton' => '.add-item', // css class 
       'deleteButton' => '.remove-item', // css class 
       'model' => $modelProducten[0], 
       'formId' => 'dynamic-form', 
       'formFields' => [ 
        'product_id', 
        'product_name', 
        'amount', 
        'price', 
       ], 
      ]); ?> 

      <div class="container-items"><!-- widgetContainer --> 
      <?php foreach ($modelProducten as $i => $modelProduct): ?> 
       <div class="item panel panel-default"><!-- widgetBody --> 
        <div class="panel-heading"> 
         <label class="panel-title pull-left">Product</label> 
         <div class="pull-right"> 
          <button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button> 
          <button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button> 
         </div> 
         <div class="clearfix"></div> 
        </div> 
        <div class="panel-body"> 
         <?php 
          // necessary for update action. 
          if (! $modelProduct->isNewRecord) { 
           echo Html::activeHiddenInput($modelProduct, "[{$i}]id"); 
          } 
         ?> 
         <div class="row"> 
          <div class="col-sm-3"> 
         <?= $form->field($modelProduct, "[{$i}]product_id")->textInput(['maxlength' => true]) ?> 
          </div> 
          <div class="col-sm-3"> 
           <?= $form->field($modelProduct, "[{$i}]product_name")->textInput(['maxlength' => true]) ?> 
          </div> 
          <div class="col-sm-3"> 
           <?= $form->field($modelProduct, "[{$i}]amount")->textInput(['maxlength' => true]) ?> 
          </div> 
          <div class="col-sm-3"> 
           <?= $form->field($modelProduct, "[{$i}]price")->textInput(['maxlength' => true]) ?> 
          </div> 
         </div><!-- .row --> 
        </div> 
       </div> 
      <?php endforeach; ?> 
      </div> 
      <?php DynamicFormWidget::end(); ?> 
     </div> 

    <div class="form-group"> 
     <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => 'btn btn-primary']) ?> 
    </div> 

    <?php ActiveForm::end(); ?> 

</div> 
</div> 

.

public function actionCreate() 
    { 
     $model = new Facturen(); 
     $modelProducten = [new Producten]; 
     if ($model->load(Yii::$app->request->post()) && $model->save()) 
     { 
      $modelProducten = Model::createMultiple(Producten::classname()); 
      Model::loadMultiple($modelProducten, Yii::$app->request->post()); 

      // validate all models 
      $valid = $model->validate(); 
      $valid = Model::validateMultiple($modelProducten) && $valid; 

      if ($valid) { 
       $transaction = \Yii::$app->db->beginTransaction(); 
       try { 
        if ($flag = $model->save(false)) { 
         foreach ($modelProducten as $modelProduct) 
         { 
          $modelProduct->factuur_id = $model->id; 
          if (! ($flag = $modelProduct->save(false))) { 
           $transaction->rollBack(); 
           break; 
          } 
         } 
        } 
        if ($flag) { 
         $transaction->commit(); 
         return $this->redirect(['view', 'id' => $model->id]); 
        } 
       } catch (Exception $e) { 
        $transaction->rollBack(); 
       } 
      } 
     } 
     else { 
      return $this->render('create', [ 
       'model' => $model, 
       'modelProducten' => (empty($modelProducten)) ? [new Producten] : $modelProducten 
      ]); 
     } 
    } 

마지막으로 Model.php

<?php 

namespace app\models; 
use Yii; 
use yii\helpers\ArrayHelper; 

class Model extends \yii\base\Model 
{ 
    /** 
    * Creates and populates a set of models. 
    * 
    * @param string $modelClass 
    * @param array $multipleModels 
    * @return array 
    */ 
    public static function createMultiple($modelClass, $multipleModels = []) 
    { 
     $model = new $modelClass; 
     $formName = $model->formName(); 
     $post  = Yii::$app->request->post($formName); 
     $models = []; 

     if (! empty($multipleModels)) { 
      $keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id')); 
      $multipleModels = array_combine($keys, $multipleModels); 
     } 

     if ($post && is_array($post)) { 
      foreach ($post as $i => $item) { 
       if (isset($item['id']) && !empty($item['id']) && isset($multipleModels[$item['id']])) { 
        $models[] = $multipleModels[$item['id']]; 
       } else { 
        $models[] = new $modelClass; 
       } 
      } 
     } 

     unset($model, $formName, $post); 

     return $models; 
    } 
} 

내가 너희들이 내 코드에서 probelm을 발견 할 수 있기를 바랍니다, 나는 당신이 찾을 때 뭘 잘못했는지 말해주십시오 함수를 만들 탐침. 나는이 프레임 워크를 배우려고 노력하고 있고, 실제로 포기하고 싶지 않다.

답변

0

동일한 모델에 대해 $model->save()을 두 번 호출하고있다. 두 번째 인스턴스가 : if ($flag = $model->save(false))은 두 번째 업데이트가 테이블의 모든 행에 영향을 미치지 않으므로 0을 반환합니다.
if ($model->save(false)!==false)을 사용하여 업데이트가 성공했는지 확인하십시오.

+0

그게 문제를 해결하지 못하거나 어쩌면 내가 잘못된 부분을 교체하고있는 것 같습니다. 나는 $ model-> save()를 대체해야합니까? –

+0

첫 번째 $ model-> save())를 제거합니다. 두 번째 업데이트가 테이블의 모든 행에 영향을 미치지 않으므로 동일한 값을 두 번 저장하고 두 번째 $ model-> save (false)는 0을 반환합니다. –

+0

위에서 언급했듯이 두 가지를 모두 변경 한 후에이'($ flag = $ model-> save (false))'를'$ model-> save (false)! == false'로 변경하면 – Kalu