2016-05-04 5 views
1

Я играл некоторое время, но я не могу понять, что такое ошибка или как ее решить. Все, что я могу придумать, это то, что это происходит из-за того, что мой виджет динамической формы wbranganca не знает, как действовать, когда я устанавливаю свое настраиваемое правило.Проверка динамических форм? yii2

Моя проблема: у меня есть динамические формы wbranganca, у меня есть некоторые поля, которые проверяют основные правила, такие как допустимые только целые числа или требуется, и его нельзя оставить пустым, но когда я добавляю настраиваемое правило, такое как не более чем, или правило даты, такое как не старше 5 дней, оно не отображает никаких ошибок, когда я ввожу его в поле, но когда я нажимаю на форму сохранения, я получаю белый экран. И данные не сохраняются в таблице, а это значит, что мое правило работает, я также пытаюсь использовать одно и то же правило в поле вне динамических форм, и он работает правильно, поэтому как я могу установить это правильно?

Мой контроллер:

<?php 
namespace app\controllers; 

use Yii; 
use app\models\Archive; 
use app\models\ArchiveSearch; 
use app\models\Invoices; 
use app\models\Model; 
use yii\web\Controller; 
use yii\web\NotFoundHttpException; 
use yii\filters\VerbFilter; 

/** 
* ArchiveController implements the CRUD actions for Archive model. 
*/ 
class ArchiveController extends Controller 
{ 
    public function behaviors() 
    { 
     return [ 
      'verbs' => [ 
       'class' => VerbFilter::className(), 
       'actions' => [ 
        'delete' => ['post'], 
       ], 
      ], 
     ]; 
    } 

    /** 
    * Lists all Archive models. 
    * @return mixed 
    */ 
    public function actionIndex() 
    { 
     $searchModel = new ArchiveSearch(); 
     $dataProvider = $searchModel->search(Yii::$app->request->queryParams); 

     return $this->render('index', [ 
      'searchModel' => $searchModel, 
      'dataProvider' => $dataProvider, 
     ]); 
    } 

    /** 
    * Displays a single Archive model. 
    * @param integer $id 
    * @return mixed 
    */ 
    public function actionView($id) 
    { 
     return $this->render('view', [ 
      'model' => $this->findModel($id), 
     ]); 
    } 

    /** 
    * Creates a new Archive model. 
    * If creation is successful, the browser will be redirected to the 'view' page. 
    * @return mixed 
    */ 
    public function actionCreate() 
    { 
     $model = new Archive(); 
     $modelsInvoices = [new Invoices]; 
     if (Yii::$app->request->isAjax && $model->load($_POST)) 
     { 
      Yii::$app->response->format ='json'; 
      return \yii\widgets\ActiveForm::validate($model); 
     } 

     if ($model->load(Yii::$app->request->post()) && $model->save()) 
     { 

      $modelsInvoices = Model::createMultiple(Invoices::classname()); 
      Model::loadMultiple($modelsInvoices, Yii::$app->request->post()); 

      /*if (Yii::$app->request->isAjax) { 
       Yii::$app->response->format = Response::FORMAT_JSON; 
       return ArrayHelper::merge(
        ActiveForm::validateMultiple($modelsInvoices), 
        ActiveForm::validate($model) 
       ); 
      }*/ 


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

      if ($valid) { 
       $transaction = \Yii::$app->db->beginTransaction(); 
       try { 
        if ($flag = $model->save(false)) { 
         foreach ($modelsInvoices as $modelInvoices) 
         { 
          $modelInvoices->archive_id = $model->id; 
          if (! ($flag = $modelInvoices->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, 
       'modelsInvoices' => (empty($modelsInvoices)) ? [new Invoices] : $modelsInvoices 
      ]); 
     } 
    } 

    /** 
    * Updates an existing Archive model. 
    * If update is successful, the browser will be redirected to the 'view' page. 
    * @param integer $id 
    * @return mixed 
    */ 
    public function actionUpdate($id) 
    { 
     $model = $this->findModel($id); 

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

    /** 
    * Deletes an existing Archive model. 
    * If deletion is successful, the browser will be redirected to the 'index' page. 
    * @param integer $id 
    * @return mixed 
    */ 
    public function actionDelete($id) 
    { 
     $this->findModel($id)->delete(); 

     return $this->redirect(['index']); 
    } 

    /** 
    * Finds the Archive model based on its primary key value. 
    * If the model is not found, a 404 HTTP exception will be thrown. 
    * @param integer $id 
    * @return Archive the loaded model 
    * @throws NotFoundHttpException if the model cannot be found 
    */ 
    protected function findModel($id) 
    { 
     if (($model = Archive::findOne($id)) !== null) { 
      return $model; 
     } else { 
      throw new NotFoundHttpException('The requested page does not exist.'); 
     } 
    } 
} 

Моя модель:

<?php 

namespace app\models; 

use Yii; 
use yii\db\Query; 
/** 
* This is the model class for table "invoices". 
* 
* @property integer $id 
* @property string $invoice_number 
* @property string $invoice_loadamount 
* @property string $invoice_date 
* @property integer $archive_id 
* @property string $DateProcessed 
* 
* @property Archive $archive 
*/ 
class Invoices extends \yii\db\ActiveRecord 
{ 
    /** 
    * @inheritdoc 
    */ 
    public static function tableName() 
    { 
     return 'invoices'; 
    } 

    /** 
    * @inheritdoc 
    */ 
    public function rules() 
    { 
     return [ 
      [['invoice_number', 'invoice_loadamount', 'invoice_date'], 'required'], 
      [['archive_id'], 'integer'], 
      [['DateProcessed'], 'safe'], 
      //Checks if invoice date put in is older than 5 days 
      [['invoice_date'], 'date', 'format'=>"dd-MM-yyyy", 'min'=>date("d-m-Y",strtotime('-5 days'))], 

      [['invoice_number', 'invoice_loadamount', 'invoice_date'], 'string', 'max' => 100]]; 
    } 

    /** 
    * @inheritdoc 
    */ 
    public function attributeLabels() 
    { 
     return [ 
      'id' => 'ID', 
      'invoice_number' => 'Invoice Number', 
      'invoice_loadamount' => 'Invoice Loadamount', 
      'invoice_date' => 'Invoice Date', 
      'archive_id' => 'Archive ID', 
      'DateProcessed' => 'Date Processed']; 
    } 

    /** 
    * @return \yii\db\ActiveQuery 
    */ 
    public function getArchive() 
    { 
     return $this->hasOne(Archive::className(), ['id' => 'archive_id']); 
    } 

    public function compareweight($attribute,$params) 
     { 
     $inputlp=($this->invoice_loadamount); 
     $row = (new \yii\db\Query()) 
     ->select('vehicle_lp') 
     ->from('vehicles') 
     ->where("vehicle_lp=$vehiclelp") 
     ->all(); 

     } 
} 

Мое мнение:

<?php 

use yii\helpers\Html; 
use yii\widgets\ActiveForm; 
use yii\helpers\ArrayHelper; 
use wbraganca\dynamicform\DynamicFormWidget; 
use app\models\Drivers; 
use app\models\Vehicles; 
use app\models\Invoices; 
use dosamigos\datepicker\DatePicker; 
use kartik\select2\Select2; 
use yii\bootstrap\Modal; 
use yii\helpers\Url; 
/* @var $this yii\web\View */ 
/* @var $model app\models\Archive */ 
/* @var $form yii\widgets\ActiveForm */ 
?> 

<div class="archive-form"> 

    <?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?> 
    <?= $form->field($model, 'driver_identitynum')->widget(Select2::classname(), [ 
    'data' => ArrayHelper::map(Drivers::find()->all(),'driver_identitynum', 'fullname'), 
    'language' => 'en', 
    'options' => ['placeholder' => 'Ingrese el numero de cedula...'], 
    'pluginOptions' => [ 
     'allowClear' => true], 
    ]); ?> 

     <div align="right"><?= Html::a('Add driver', ['/drivers/create'], 
     ['target'=>'_blank']); ?> 
     </div> 

    <?= $form->field($model, 'vehicle_lp')->widget(Select2::classname(), [ 
    'data' => ArrayHelper::map(Vehicles::find()->all(),'vehicle_lp', 'fulltruck'), 
    'language' => 'en', 
    'options' => ['placeholder' => 'Ingrese la placa del vehiculo...'], 
    'pluginOptions' => [ 
     'allowClear' => true 
    ], 
    ]); ?> 

    <div align="right"><?= Html::a('Add vehicle', ['/vehicles/create'], 
     ['target'=>'_blank']); ?> 
     </div> 

    <div class="row"> <div class="panel panel-default"> 
     <div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i> Addresses</h4></div> 
     <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' => 4, // 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' => $modelsInvoices[0], 
       'formId' => 'dynamic-form', 
       'formFields' => [ 
        'invoice_number', 
        'invoice_loadamount', 
        'invoice_date', 
       ], 
      ]); ?> 

      <div class="container-items"><!-- widgetContainer --> 
      <?php foreach ($modelsInvoices as $i => $modelInvoices): ?> 
       <div class="item panel panel-default"><!-- widgetBody --> 
        <div class="panel-heading"> 
         <h3 class="panel-title pull-left">Address</h3> 
         <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 (! $modelInvoices->isNewRecord) { 
           echo Html::activeHiddenInput($modelInvoices, "[{$i}]id"); 
          } 
         ?> 
         <div class="row"> 
          <div class="col-sm-6"> 
           <?= $form->field($modelInvoices, "[{$i}]invoice_number")->textInput(['maxlength' => true]) ?> 
          </div> 
          <div class="col-sm-6"> 
           <?= $form->field($modelInvoices, "[{$i}]invoice_loadamount")->textInput(['maxlength' => true]) ?> 
          </div> 
          <div class="col-sm-6"> 
           <?= $form->field($modelInvoices, "[{$i}]invoice_date")->widget(
    DatePicker::className(), [ 
     // inline too, not bad 
     'inline' => false, 
     // modify template for custom rendering 
     //'template' => '<div class="well well-sm" style="background-color: #fff; width:250px">{input}</div>', 
     'clientOptions' => [ 
      'autoclose' => true, 
      'format' => 'dd-MM-yyyy' 
     ] 
    ]);?> 

          </div> 
         </div><!-- .row --> 
         <div class="row"> 

        </div> 
       </div> 
      <?php endforeach; ?> 
      </div> 
      <?php DynamicFormWidget::end(); ?> 
     </div> 
    </div> 
</div> 



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

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

</div> 
+0

Просто кода модели достаточно;) –

ответ

2

Посмотреть

Put ['enableAjaxValidation' => true] в поле.

<div class="col-sm-6"> 
    <?= $form->field($modelInvoices, "[{$i}]invoice_date",['enableAjaxValidation' => true])->widget(
     DatePicker::className(), [ 
     'inline' => false, 
     'clientOptions' => [ 
      'autoclose' => true, 
      'format' => 'dd-MM-yyyy' 
      ] 
     ]); 
    ?> 
</div> 

Контроллер

Добавить use yii\web\Response; & use yii\widgets\ActiveForm;

И изменить структуру коды в соответствии с приведенным ниже кодом.

<?php 
// These two lines are mandatory. 
use yii\web\Response; 
use yii\widgets\ActiveForm; 

public function actionCreate() 
{ 
    $model = new Archive(); 
    $modelsInvoices = [new Invoices]; 

    $modelsInvoices = Model::createMultiple(Invoices::classname()); 
    Model::loadMultiple($modelsInvoices, Yii::$app->request->post()); 

    if (Yii::$app->request->isAjax) 
    { 
     Yii::$app->response->format = Response::FORMAT_JSON; 
     return ActiveForm::validate($modelsInvoices); 

    } elseif ($model->load(Yii::$app->request->post()) && $model->save()) { 
     . 
     . 
    } 
    . 
    . 
} 

Будет работать.

Для получения дополнительной информации, пожалуйста, нажмите Validating unique email using DynamicFormWidget - Yii2

Смежные вопросы