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

Posted

技术标签:

【中文标题】通过yii2中的checkboxcolumn将多行插入表格【英文标题】:Insert multiple rows into table by checkboxcolumn in yii2 【发布时间】:2017-03-14 07:36:54 【问题描述】:

我有一个餐桌原材料。这些字段是 -rmname, usedate, useqty, unitcost, productname, chargenumber。我在表单中添加了一个带有复选框列的 gridview(来自 rmtemplate 表)。网格视图包含列productname, rmname, qty, unitcost。如何在表格原材料中插入选中的行以及 usedate、chargenumber(来自各自的文本框)。

我检查了ActiveRecord batch insert (yii2),但不知道如何将它与 checkbocolumn 一起使用。

检查了How I can process a checkbox column from Yii2 gridview? - 不太确定。

检查 Yii2 How to properly create checkbox column in gridview for bulk actions? - 我认为它没有使用 activeform。

form.php

<?php

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

/* @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-12 col-sm-12 col-lg-12">
            <?= $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-12 col-sm-12 col-lg-12">
            <?= GridView::widget([
            'dataProvider' => $dataProvider2,
            'filterModel' => $searchModel2,
            'columns' => [
                ['class' => 'kartik\grid\CheckboxColumn'],

                //'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',
                [
                 'attribute' => 'unitcost',
                 'value' => 'unitcost.unitcost',
                ],

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




    <?= $form->field($model, 'chargenumber')->textInput()->hiddenInput()->label(false) ?>



    <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);
      $('#rawmaterial-chargenumber').attr('value',data.chargeno);
  
  );
);
EOD;
$this->registerJs($script);
/*end getting the chargeno */
?>

它看起来像下面。

CreateAction 看起来像 -

public function actionCreate()
    
        $model = new Rawmaterial();
        $searchModel2 = new RmtemplateSearch();
        $dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams);

        if (isset($_POST['submit']))  

            if ($_POST('submit')  == 'create_update' )  
            // then perform the insert 
                if ($model->load(Yii::$app->request->post()) && $model->save()) 
                return $this->redirect(['view', 'id' => $model->id]);
                 else 
                    return $this->render('create', [
                        'model' => $model,
                        'searchModel2' => $searchModel2,
                        'dataProvider2' => $dataProvider2,
                    ]);
                
            
              else 
                 // no insert  but render for filter ..
                return $this->render('create', [
                        'model' => $model,
                        'searchModel2' => $searchModel2,
                        'dataProvider2' => $dataProvider2,
                    ]);
            


    

更新 RawMaterialForm.php

<?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

    /**
     * @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',
            'vname' => 'Vname',
            'challan' => 'Challan',
            'purchasedate' => 'Purchasedate',
            'purchaseqty' => 'Purchaseqty',
            'rate' => 'Rate',
            '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;


错误

【问题讨论】:

看起来你需要准备额外的模型来处理表单数据。我猜您想将选定的 GridView 行模型的字段复制到原材料表,但您从未提及您希望如何复制它们,我只能假设应该复制相同名称的字段但是 useqty 呢?还需要原材料的主键。 gridview 中的“qty”列应该输入到原材料表的“useqty”中。此外,原材料“id”的主键是自动增量。现在,我不太确定如何将这些列或行复制到原材料表中。这就是为什么它没有取得那么大的进展。 【参考方案1】:

根据我的理解,你必须做两件事。

首先,您必须将网格视图的所有选中行数据作为数组或对象获取。你可以从Get Grid Data 看到如何做到这一点。 其次,您必须更改创建操作以处理从该网格获取的数据。你可以向Batch Insert寻求帮助

希望对你有帮助...

【讨论】:

【参考方案2】:

准备其他模型,例如 RawMaterialForm,其属性将从 ActiveForm usedatechargenumberrmtemplate_ids 中获取。最后一个是 GridView ID 数组。记得在属性的 RawMaterialForm 中添加rules()

视图 - 只是 GridView 需要一些调整。扩展 Checkbox 列的配置。

[
    'class' => 'kartik\grid\CheckboxColumn',
    'name' => 'RawMaterialForm[rmtemplate_ids]',
    'checkboxOptions' => function ($model, $key, $index, $column) 
        return ['value' => $model->id];
    
],

动作

public function actionCreate()

    $model = new RawMaterialForm();

    if ($model->load(Yii::$app->request->post()) && $model->save()) 
        return $this->redirect(
            // 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,
    ]);

RawMaterialForm 的save() 方法

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;

这会将每个选定的行复制到一个新的 Rawmaterial 行,其中包含来自 ActiveForm 的附加输入。 万一$rawMaterial保存检查$rawMaterial-&gt;errors属性出错。

一般警告 - 根据系统性能,如果一次选择多行,这可能会很慢(甚至是致命的)。

【讨论】:

抱歉回复晚了。我已经按照我的理解放置了代码。我已经在问题的更新中给出了我目前的职位。现在我收到了问题中所示的错误。然后我尝试在 RawMaterialForm 模型中添加 public $rmtemplate_ids 。然后错误消失了,但只有使用过的数据被插入到原材料表中,而且也只有一次。 好吧,就像我在第一句话中写的那样,你需要准备这个模型和所有属性,这意味着你必须列出所有属性并为它们添加验证规则。 我想我已经将它写在 RawMaterialForm 模型中,如问题所示(在更新部分)。如果这不是你的意思,那么请举一个例子,我会做剩下的。我不太明白。

以上是关于通过yii2中的checkboxcolumn将多行插入表格的主要内容,如果未能解决你的问题,请参考以下文章

YII2 Gridview 批量删除

yii2 pjax使用

yii2 gridview checkbox

yii2 gridview 怎么加checkbox

如何从 Select2 Widget Yii2 将多个值保存到数据库

Yii2中的线程数据