通过yii2

时间:2016-11-01 07:00:28

标签: yii2

我有一张表原料。字段为 - rmname, usedate, useqty, unitcost, productname, chargenumber。我在表单中添加了一个gridview(来自rmtemplate表),其中包含一个checkboxcolumn。 gridview包含列productname, rmname, qty, unitcost。如何在表rawmaterial中插入已检查的行以及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 */
?>

它看起来像下面。 enter image description here

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',
        ];
    }
}

RawmaterialController

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

错误 enter image description here

2 个答案:

答案 0 :(得分:0)

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

  • 首先,您必须将网格视图的所有已检查行数据作为数组或对象获取。您可以在Get Grid Data
  • 中查看如何执行此操作
  • 其次,您必须更改创建操作以处理从该网格中获取的数据。您可以从Batch Insert
  • 获取帮助

希望它有所帮助...

答案 1 :(得分:0)

准备其他模型,例如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->errors属性。

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