yii2单一模型的动态形式

时间:2017-01-30 13:26:33

标签: php yii2 yii2-advanced-app

我使用webraganca为单一模型工作yii2高级动态表单。但由于以下错误,我无法继续前进。任何帮助都非常感激。

enter image description here

我的代码如下: Controller.php这样     

namespace frontend\controllers;

use Yii;
use frontend\models\Ireturn;
use frontend\models\IreturnSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Json;
use frontend\models\Model;
/**
  * IreturnController implements the CRUD actions for Ireturn model.
*/
class IreturnController extends Controller
 {
    /**
    * @inheritdoc
    */
  public function behaviors()
   {
       return [
           'verbs' => [
               'class' => VerbFilter::className(),
                 'actions' => [
                    'delete' => ['POST'],
                ],
             ],
        ];
    }

      /**
      * Lists all Ireturn models.
      * @return mixed
      */
     public function actionIndex()
     {
        $searchModel = new IreturnSearch();
         $dataProvider =    $searchModel->search(Yii::$app->request->queryParams);
      if(Yii::$app->request->post('hasEditable'))
        {
             $ireturnId = Yii::$app->request->post('editableKey');
             $ireturn = Ireturn::findOne($ireturnId);
             $out = Json::encode(['output'=>'','message'=>'']);
             $post = [];
             $posted = current($_POST['Ireturns']);
             $post['Ireturns']= $posted;
             if($ireturn->load($post))
               {
                  $ireturn->save();
                  $output ='my values';
                  $out = Json::encode(['output'=>$output,'message'=>'']);
              }
              return;
          }
            return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            ]);
        }

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

      /**
        * Creates a new Ireturn model.
        * If creation is successful, the browser will be redirected to the 'view' page.
        * @return mixed
       */

     public function actionCreate()
      {
         $model = new Ireturn();
         $modelsAddress = [new Ireturn];

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

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

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

           if ($valid) {
              $transaction = \Yii::$app->db->beginTransaction();

                try {
                   if ($flag = $model->save(false)) {
                       foreach ($modelsAddress as $modelAddress) {
                          $modelAddress->id = $model->id;
                           if (! ($flag = $modelAddress->save(false))) {
                            $transaction->rollBack();
                            break;
                          }
                       }
                    }

                   if ($flag) {
                     $transaction->commit();
                     return $this->redirect(['view', 'id' => $model->id]);
                   }
                } catch (Exception $e) {
                  $transaction->rollBack();
               }
            }
          }

         return $this->render('create', [
          'model' => $model,
          'modelsAddress' => (empty($modelsAddress)) ? [new Ireturn] :   $modelsAddress
    ]);   

    /*$model = new Ireturn();
     $modelsAddress =  [new Ireturn];

     if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['view', 'id' => $model->id]);
       } else {
        return $this->render('create', [
            'model' => $model,
            'modelsAddress' => (empty($modelsAddress)) ? [new Ireturn] : $modelsAddress
            ]);
        }*/
      }

     /**
      * Updates an existing Ireturn 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 Ireturn 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 Ireturn model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Ireturn the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
       if (($model = Ireturn::findOne($id)) !== null) {
        return $model;
       } else {
        throw new NotFoundHttpException('The requested page does not exist.');
       }
     }
 /*public function actionEditableDemo() {
  $model = new Ireturn(); // your model can be loaded here

   // Check if there is an Editable ajax request
    if (isset($_POST['hasEditable'])) {
    // use Yii's response format to encode output as JSON
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

    // read your posted model attributes
    if ($model->load($_POST[])) {
        // read or convert your posted information
        $value = $model->functional;

        // return JSON encoded output in the below format
        return ['output'=>$value, 'message'=>''];

        // alternatively you can return a validation error
        // return ['output'=>'', 'message'=>'Validation error'];
     }
     // else if nothing to do always return an empty JSON encoded output
      else {
          return ['output'=>'', 'message'=>''];
      }
   }

   // Else return to rendering a normal view
    return $this->render('view', ['model'=>$model]);
   }*/
  }

_form.php这个      

 use yii\helpers\Html;
 use yii\helpers\ArrayHelper;
 use yii\widgets\ActiveForm;
 use backend\models\Items;
 use backend\models\Departments;
 use kartik\select2\Select2;
 use dosamigos\datepicker\DatePicker;
 use yii\web\View;
 use wbraganca\dynamicform\DynamicFormWidget;
 use common\models\User;

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

 <div class="ireturn-form">
       <?php $form = ActiveForm::begin(['id' => 'dynamic-form','options'=>['class'=>'well'],]); ?>
      <div class="panel panel-default" >
            <!--<div class="panel-heading">
              <h4><i class="glyphicon glyphicon-envelope"></i> Items              
            </h4>
           </div>-->
          <div class="panel-body">
              <div class="row">

                 <div class="col-xs-4"> 
                <?= $form->field($model, 'dept_id')->widget(Select2::classname(), [
                    'data' => ArrayHelper::map(Departments::find()->all(),'id','dept_name'),
                    'language' => 'en',
                    'options' => ['placeholder' => 'Select departments ...'],
                    'pluginOptions' => [
                    'allowClear' => true
                    ],
                ]);
                ?>
             </div>
              <div class="col-xs-3">
                <?= $form->field($model, 'voucher_no')->textInput(['maxlength' => true])?>
              </div>
           </div>
            <!--    <div class="panel panel-default">-->
            <!--     <div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i> Items</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' => $modelsAddress[0],
            'formId' => 'dynamic-form',
            'formFields' => [
                'items_id',
                'unit',
                'amount',
                'functional',
             ],
           ]); ?>
         <div class="container-items"><!-- widgetContainer -->
            <div class="item panel panel-default"><!-- widgetBody -->
                <div class="panel-heading">
                    <h3 class="panel-title pull-left"> <i class="glyphicon glyphicon-envelope"></i>Item</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>
            <?php foreach ($modelsAddress as $i => $modelAddress): ?>

                <div class="panel-body">
                    <?php
                        // necessary for update action.
                        if (! $modelAddress->isNewRecord) {
                            echo Html::activeHiddenInput($model, "[{$i}]id");
                        }
                    ?>
                    <div class="row">
                        <div class="col-sm-3">
                            <?= $form->field($modelAddress, "[{$i}]items_id")->dropDownList(
                                         ArrayHelper::map(Items::find()->all(),'id','item_name'),
                                        ['prompt'=>'select items']) ?>
                        </div>
                        <div class="col-sm-3">
                            <?= $form->field($modelAddress, "[{$i}]unit")->textInput(['maxlength' => true]) ?>
                        </div>                        
                        <div class="col-sm-3">
                            <?= $form->field($modelAddress, "[{$i}]amount")->textInput(['maxlength' => true]) ?>
                        </div>
                        <div class="col-sm-3">
                            <?= $form->field($modelAddress, "[{$i}]functional")->textInput(['maxlength' => true]) ?>
                        </div>
                    </div><!-- .row -->
                </div>

            <?php endforeach; ?>
            </div>
          </div>
          <?php DynamicFormWidget::end(); ?>
      <!--        </div>-->
      <!--    </div>-->
         <div class="padding-v-md">

            <div class="line line-dashed"></div>

        </div>

        <div class="row">
             <div class="col-xs-4">
                <?= $form->field($model,'user_id')->dropDownList(
                        ArrayHelper::map(User::find()->all(),'id','full_name'),
                        ['prompt'=>'select employees'])
                 ?>
                <?= $form->field($model,'head_id')->dropDownList(
                        ArrayHelper::map(User::find()->all(),'id','full_name'),
                        ['prompt'=>'select dept heads'])
                 ?>
                <?= $form->field($model,'man_id')->dropDownList(
                        ArrayHelper::map(User::find()->all(),'id','full_name'),
                        ['prompt'=>'select stoke managers'])
                 ?>
                <?= $form->field($model,'keeper_id')->dropDownList(
                        ArrayHelper::map(User::find()->all(),'id','full_name'),
                        ['prompt'=>'select stoke keepers'])
                 ?>  
          </div>        
            <div class="col-xs-4">
             <?=$form->field($model, 'emp_date')->widget(
                    DatePicker::className(), [
                    'inline' => false, 
                    'clientOptions' => [
                    'autoclose' => true,
                    'format' => 'yyyy-mm-dd'
                    ]
                ]);?>

                <?=$form->field($model, 'head_date')->widget(
                    DatePicker::className(), [
                        'inline' => false, 
                        'clientOptions' => [
                        'autoclose' => true,
                        'format' => 'yyyy-mm-dd'
                        ]
                ]);?>

                <?=$form->field($model, 'man_date')->widget(
                    DatePicker::className(), [
                        'inline' => false, 
                        'clientOptions' => [
                        'autoclose' => true,
                        'format' => 'yyyy-mm-dd'
                        ]
                ]);?>

                <?=$form->field($model, 'keeper_date')->widget(
                    DatePicker::className(), [
                        'inline' => false, 
                        'clientOptions' => [
                        'autoclose' => true,
                        'format' => 'yyyy-mm-dd'
                        ]
                ]);?>
                 </div>
               </div>
            </div>
        <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 = <<<EOD
         $(".dynamicform_wrapper").on("beforeInsert", function(e, item) {
          console.log("beforeInsert");
     });

      $(".dynamicform_wrapper").on("afterInsert", function(e, item) {
        console.log("afterInsert");
      });

      $(".dynamicform_wrapper").on("beforeDelete", function(e, item) {
         if (! confirm("Are you sure you want to delete this item?")) {
        return false;
        }
        return true;
      });

      $(".dynamicform_wrapper").on("afterDelete", function(e) {
       console.log("Deleted item!");
      });

       $(".dynamicform_wrapper").on("limitReached", function(e, item) {
        alert("Limit reached");
      });
      EOD;
      $this->registerJs($script, View::POS_END);        
      ?>

1 个答案:

答案 0 :(得分:0)

不清楚为什么要将子项目保存到与父项目相同的表中。

请查看您的代码,

$modelAddress->id = $model->id;

如果您将其保存在同一个表中且id属性具有唯一约束,则不能为父和子分配相同的ID

替代方案,您可以创建一个新列[refference_id]来引用父ID

    $modelAddress->refference_id = $model->id;