将网格视图中的选中行插入到 yii2 中的表中

Posted

技术标签:

【中文标题】将网格视图中的选中行插入到 yii2 中的表中【英文标题】:Insert checked rows from a gridview to a table in yii2 【发布时间】:2017-04-29 08:53:54 【问题描述】:

参考Insert multiple rows into table by checkboxcolumn in yii2 我在问这个问题。我正在尝试将数据插入原材料表。将插入的数据来自 rmtemplate 表。我添加了一个网格视图,它以原材料形式从 rmtemplate 加载数据。除了选中的行之外,我还有两个字段 usedate,chargenumber 将插入每一行。

通过下面的代码,它只插入一行,除了chargenumber,usedate之外没有其他数据

_form.php

<?php

use yii\helpers\html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
use kartik\grid\GridView;
use dosamigos\datepicker\DatePicker;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use frontend\models\Rmtemplate;
use yii\helpers\Json;
use yii\web\View;

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

<div class="rawmaterial-form">

    <?php $form = ActiveForm::begin(); ?>
    <div class="form-group">
        <div class="col-xs-6 col-sm-6 col-lg-6">
            <?= $form->field($model, 'usedate')->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,
                    'todayHighlight' => true,
                    'format' => 'yyyy-mm-dd'
                ]
            ]);?>
        </div>

        <div class="col-xs-6 col-sm-6 col-lg-6">
            <?= $form->field($model, 'chargenumber')->textInput(['readOnly' => true]) ?>
        </div>

        <div class="col-xs-12 col-sm-12 col-lg-12">
            <?= GridView::widget([
            'dataProvider' => $dataProvider2,
            'filterModel' => $searchModel2,
            //'id' => $mytable,
            'columns' => [
                [
                'class' => 'kartik\grid\CheckboxColumn',
                'name' => 'RawMaterialForm[rmtemplate_ids]',
                'checkboxOptions' => function ($model, $key, $index, $column) 
                    return ['value' => $model->id];
                
                ],

                //'id',
                //'productname',
                [
                    'attribute'=>'productname',
                    'filterType'=>GridView::FILTER_SELECT2,
                    'filter'=>ArrayHelper::map(Rmtemplate::find()->orderBy(['productname' => SORT_ASC])->asArray()->all(), 'productname', 'productname'),
                    'filterWidgetOptions'=>[
                    'pluginOptions'=>['allowClear'=>true],
                                        ],
                    'filterInputOptions'=>['placeholder'=>'Charge Name'],
                ],
                'rmname',
                'qty',
                'cost',

                //['class' => 'yii\grid\ActionColumn'],
            ],
        ]); ?>
        </div>
    </div>  


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

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

</div>

<?php
/* start getting the chargeno */
$script = <<<EOD
  $(window).load(function()
  $.get('index.php?r=rmprod/rawmaterial/get-for-chargeno', orderid : 1 , function(data)
      //alert(data);
      var data = $.parseJSON(data);
      $('#rawmaterialform-chargenumber').attr('value',data.chargeno);
  
  );
);
EOD;
$this->registerJs($script);
/*end getting the chargeno */
?>

Rwmaterial 模型

<?php

namespace frontend\modules\rmprod\models;

use Yii;

/**
 * This is the model class for table "rawmaterial".
 *
 * @property integer $id
 * @property string $vname
 * @property integer $rm_chid
 * @property string $challan
 * @property string $purchasedate
 * @property string $purchaseqty
 * @property string $rate
 * @property string $rmname
 * @property string $usedate
 * @property string $useqty
 * @property string $unitcost
 * @property string $productname
 * @property integer $chargenumber
 *
 * @property Pursum $rmCh
 */
class Rawmaterial extends \yii\db\ActiveRecord

    public $mytable;
    /**
     * @inheritdoc
     */
    public static function tableName()
    
        return 'rawmaterial';
    

    /**
     * @inheritdoc
     */
    public function rules()
    
        return [
            [['rm_chid', 'chargenumber'], 'integer'],
            [['purchasedate', 'usedate'], 'safe'],
            [['vname', 'productname'], 'string', 'max' => 40],
            [['challan'], 'string', 'max' => 20],
            [['purchaseqty', 'rmname', 'useqty'], 'string', 'max' => 50],
            [['rate', 'unitcost'], 'string', 'max' => 10],
            [['rm_chid'], 'exist', 'skipOnError' => true, 'targetClass' => Pursum::className(), 'targetAttribute' => ['rm_chid' => 'ps_chid']],
        ];
    

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    
        return [
            'id' => 'ID',
            'vname' => 'Vname',
            'rm_chid' => 'Rm Chid',
            'challan' => 'Challan',
            'purchasedate' => 'Purchasedate',
            'purchaseqty' => 'Purchaseqty',
            'rate' => 'Rate',
            'rmname' => 'Rmname',
            'usedate' => 'Usedate',
            'useqty' => 'Useqty',
            'unitcost' => 'Unitcost',
            'productname' => 'Productname',
            'chargenumber' => 'Chargenumber',
        ];
    

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRmCh()
    
        return $this->hasOne(Pursum::className(), ['ps_chid' => 'rm_chid']);
    

RawmaterialForm 模型

<?php

namespace frontend\modules\rmprod\models;

use Yii;

/**
 * This is the model class for table "rawmaterial".
 *
 * @property integer $id
 * @property string $vname
 * @property string $challan
 * @property string $purchasedate
 * @property string $purchaseqty
 * @property string $rate
 * @property string $rmname
 * @property string $usedate
 * @property string $useqty
 * @property string $unitcost
 * @property string $productname
 * @property integer $chargenumber
 */
class RawMaterialForm extends \yii\db\ActiveRecord

    public $rmtemplate_ids;
    public $mytable;
    /**
     * @inheritdoc
     */
    public static function tableName()
    
        return 'rawmaterial';
    

    /**
     * @inheritdoc
     */
    // public function rules()
    // 
    //     return [
    //         [['purchasedate', 'usedate'], 'safe'],
    //         [['chargenumber'], 'integer'],
    //         [['vname', 'productname'], 'string', 'max' => 40],
    //         [['challan'], 'string', 'max' => 20],
    //         [['purchaseqty', 'rmname', 'useqty'], 'string', 'max' => 50],
    //         [['rate', 'unitcost'], 'string', 'max' => 10],
    //     ];
    // 

    public function rules()
    
        return [
            [['usedate'], 'safe'],
            [['chargenumber'], 'integer'],
            [['productname'], 'string', 'max' => 40],
            [['rmname', 'useqty'], 'string', 'max' => 50],
            [['unitcost'], 'string', 'max' => 10],
            [['rmtemplate_ids'], 'safe'],
        ];
    

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    
        return [
            'id' => 'ID',
            'rmname' => 'Rmname',
            'usedate' => 'Usedate',
            'useqty' => 'Useqty',
            'unitcost' => 'Unitcost',
            'productname' => 'Productname',
            'chargenumber' => 'Chargenumber',
        ];
    


原材料控制器

<?php

namespace frontend\modules\rmprod\controllers;

use Yii;
use frontend\models\Rawmaterial;
use frontend\modules\rmprod\models\RawmaterialSearch;
use frontend\modules\rmprod\models\RmtemplateSearch;
use frontend\modules\rmprod\models\RawMaterialForm;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Json;

/**
 * RawmaterialController implements the CRUD actions for Rawmaterial model.
 */
class RawmaterialController extends Controller

    /**
     * @inheritdoc
     */
    public function behaviors()
    
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    

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

        $searchModel2 = new RmtemplateSearch();
        $dataProvider2 = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,

            'searchModel2' => $searchModel2,
            'dataProvider2' => $dataProvider2,
        ]);
    

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

    /**
     * Creates a new Rawmaterial model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()

    $model = new RawMaterialForm();

    if ($model->load(Yii::$app->request->post()) && $model->save()) 
        return $this->redirect(
            ['create']
            // redirect to where you want
        );
    

    $searchModel2 = new RmtemplateSearch();
    $dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams);

    return $this->render('create', [
        'model' => $model,
        'searchModel2' => $searchModel2,
        'dataProvider2' => $dataProvider2,
    ]);


    /**
     * Updates an existing Rawmaterial 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 Rawmaterial 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']);
    
    public function actionGetForChargeno($orderid)
    
        $rates = Rawmaterial::find()->select('(max(chargenumber) + 1) as chargeno')->asArray()->one();
        echo Json::encode($rates);
    
    /**
     * Finds the Rawmaterial model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Rawmaterial the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    
        if (($model = Rawmaterial::findOne($id)) !== null) 
            return $model;
         else 
            throw new NotFoundHttpException('The requested page does not exist.');
        
    
    public function save()
    
        try 
            if ($this->validate()) 
                // assuming Rmtemplate is the model used in RmtemplateSearch
                $selectedRmtemplate = Rmtemplate::find()->where(['id' => $this->rmtemplate_ids]);
                foreach ($selectedRmtemplate->each() as $rm) 
                    $rawMaterial = new Rawmaterial();
                    $rawMaterial->rmname = $rm->rmname;
                    $rawMaterial->usedate = $this->usedate;
                    $rawMaterial->useqty = $rm->qty;
                    $rawMaterial->unitcost = $rm->unitcost;
                    $rawMaterial->productname = $rm->productname;
                    $rawMaterial->chargenumber = $this->chargenumber;
                    if (!$rawMaterial->save()) 
                        throw new \Exception('Error while saving rawMaterial!');
                    
                
                return true;
            
         catch (\Exception $exc) 
            \Yii::error($exc->getMessage());
        
        return false;
    

调试工具栏显示如下 -

将保存功能移至 RawmaterialForm 模型后

变量转储

public function actionCreate()
    
    $model = new RawMaterialForm();

    if ($model->load(Yii::$app->request->post()) && $model->validate()) 
        if($model->saveRawTemlate($model)) 
            // success message
         else 
            // failure message
        
        return $this->redirect(['create']);
    
    if ($rawMaterial->save())  throw new \Exception('Error while saving rawMaterial!');  else  var_dump($rawMaterial->getErrors());

    $searchModel2 = new RmtemplateSearch();
    $dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams);

    return $this->render('create', [
        'model' => $model,
        'searchModel2' => $searchModel2,
        'dataProvider2' => $dataProvider2,
    ]);
    

函数中的Vardump

public function saveRawTemlate($model)

    try 
        // assuming Rmtemplate is the model used in RmtemplateSearch
        $selectedRmtemplate = Rmtemplate::find()->where(['id' => $model->rmtemplate_ids]);
        foreach ($selectedRmtemplate->each() as $rm) 
            $rawMaterial = new Rawmaterial();
            $rawMaterial->rmname = $rm->rmname;
            $rawMaterial->usedate = $model->usedate;
            $rawMaterial->useqty = $rm->qty;
            $rawMaterial->unitcost = $rm->unitcost;
            $rawMaterial->productname = $rm->productname;
            $rawMaterial->chargenumber = $model->chargenumber;
            if (!$rawMaterial->save()) 
                throw new \Exception('Error while saving rawMaterial!');
            
        
    return true;
     catch (\Exception $exc) 
        \Yii::error($exc->getMessage());
    
    if ($rawMaterial->save())  throw new \Exception('Error while saving rawMaterial!');  else  var_dump($rawMaterial->getErrors());
    return false;

函数 saveRawTemplate

public function saveRawTemlate($model)

    try 
        // assuming Rmtemplate is the model used in RmtemplateSearch
        //$selectedRmtemplate = Rmtemplate::find()->where(['id' => $model->rmtemplate_ids]);
        $selectedRmtemplate = Rmtemplate::find()->where(['id' => $model->rmtemplate_ids])->all();
        var_dump($selectedRmtemplate);
        foreach ($selectedRmtemplate->each() as $rm) 
            $rawMaterial = new Rawmaterial();
            $rawMaterial->rmname = $rm->rmname;
            $rawMaterial->usedate = $model->usedate;
            $rawMaterial->useqty = $rm->qty;
            $rawMaterial->unitcost = $rm->unitcost;
            $rawMaterial->productname = $rm->productname;
            $rawMaterial->chargenumber = $model->chargenumber;
            if (!$rawMaterial->save()) 
                //var_dump($rawMaterial->getErrors()); exit;
                throw new \Exception('Error while saving rawMaterial!');
            
        
    return true;
     catch (\Exception $exc) 
        \Yii::error($exc->getMessage());
    

    return false;

输出

【问题讨论】:

因为从未调用过save() 方法。对于控制器,我猜是$this-&gt;save()save() 函数应该在模型中,如果不需要,不要尝试覆盖默认模型方法。 您的意思是保存功能应该在 RawmaterialForm 模型中?我已经把它放在那里并且它给出了错误 - 声明 frontend\modules\rmprod\models\RawMaterialForm::save() 必须与 yii\db\ActiveRecordInterface::save($runValidation = true, $attributeNames = NULL) 兼容而且我不确定将 $this->save() 放在控制器操作中的哪个位置。请告诉我如何解决它。 save() 是一种 ActiveRecordInterface 方法,用于保存您尝试覆盖的数据,将其重命名为将此方法移动到模型并寻找如何使用 foreach 或使用批量插入来保存数据。现在很忙,有时间会回复的。 好的。请告诉我。 【参考方案1】:

控制器

public function actionCreate()

    $model = new RawMaterialForm();

    if ($model->load(Yii::$app->request->post()) && $model->validate()) 
        if($model->saveRawTemlate($model)) 
            // success message
         else 
            // failure message
        
        return $this->redirect(['create']);
    

    $searchModel2 = new RmtemplateSearch();
    $dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams);

    return $this->render('create', [
        'model' => $model,
        'searchModel2' => $searchModel2,
        'dataProvider2' => $dataProvider2,
    ]);

型号

public function saveRawTemlate($model)

    try 
        // assuming Rmtemplate is the model used in RmtemplateSearch
        $selectedRmtemplate = Rmtemplate::find()->where(['id' => $model->rmtemplate_ids])->all();
        foreach ($selectedRmtemplate as $rm) 
            $rawMaterial = new Rawmaterial();
            $rawMaterial->rmname = $rm['rmname'];
            $rawMaterial->usedate = $model->usedate;
            $rawMaterial->useqty = $rm['qty'];
            $rawMaterial->unitcost = $rm['unitcost'];
            $rawMaterial->productname = $rm['productname'];
            $rawMaterial->chargenumber = $model->chargenumber;
            if (!$rawMaterial->save()) 
                throw new \Exception('Error while saving rawMaterial!');
            
        
    return true;
     catch (\Exception $exc) 
        \Yii::error($exc->getMessage());
    
    return false;

【讨论】:

嗨疯狂的骷髅,感谢您的回答。但它没有在原材料表中插入任何东西。 if ($rawMaterial-&gt;save()) throw new \Exception('Error while saving rawMaterial!'); else var_dump($rawMaterial-&gt;getErrors()); 您的意思是在控制器中?我在问题中添加了带有 vardump 的代码。 @Tanmay。 saveRawTemlate() 函数内的模型中没有。 我已在函数中添加并在问题中添加了当前代码。请让我知道它是否正确。它在保存 rawMaterial 时给出异常 - 错误!

以上是关于将网格视图中的选中行插入到 yii2 中的表中的主要内容,如果未能解决你的问题,请参考以下文章

通过yii2中的checkboxcolumn将多行插入表格

将列表的内容数据绑定到数据网格

Yii2过滤网格视图,带有多个$ _GET参数

Yii2- Select2 按钮作为网格视图过滤器不过滤

笔记:实现网格视图数据选择

使用 Jquery 从 Razor 视图中的网格表中以模态显示整个字典