validaciones personalizadas framework datos createcommand consultas app yii2

personalizadas - Insertar varias filas en la tabla por casilla de verificación en yii2



yii2 odbc (2)

Prepare un modelo adicional como RawMaterialForm con propiedades que se tomarán de ActiveForm usedate , chargenumber y rmtemplate_ids . El último es la matriz de ID de GridView. Recuerde agregar rules() en RawMaterialForm para las propiedades.

La vista : solo GridView necesita algunos ajustes. Extienda la configuración para la columna de casilla de verificación.

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

La acción :

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

Método save() RawMaterialForm :

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

Esto copiará cada fila seleccionada en una nueva fila Rawmaterial con entradas adicionales de ActiveForm. En caso de errores en la propiedad $ rawMaterial saving check $rawMaterial->errors .

Advertencia razonable: dependiendo del rendimiento del sistema, esto puede ser lento (o incluso fatal) en caso de seleccionar muchas filas a la vez.

Tengo una tabla sin materia prima. Los campos son - rmname, usedate, useqty, unitcost, productname, chargenumber . He agregado una vista de cuadrícula (que viene de la tabla rmtemplate) con una casilla de verificación en el formulario. La vista de cuadrícula contiene columnas productname, rmname, qty, unitcost . ¿Cómo puedo insertar las filas marcadas junto con usedate, chargenumber (que provienen de las respectivas cajas de texto) en la tabla rawmaterial?

Revisé la inserción por lotes de ActiveRecord (yii2) pero no obtuve cómo usarla con checkbocolumn.

Comprobado ¿Cómo puedo procesar una columna de casilla de verificación de Yii2 gridview? - No estoy seguro con eso.

Yii2 revisado ¿Cómo crear correctamente la columna de casilla de verificación en gridview para acciones masivas? - Creo que no está usando 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 */ ?>

Y se ve abajo.

CreateAction se ve como ...

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

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

Error


Según mi entendimiento, tienes que hacer dos cosas.

  • En primer lugar, debe tomar todos los datos de filas verificadas de la vista de cuadrícula como una matriz u objeto. Puede ver cómo hacerlo desde Obtener datos de cuadrícula .
  • En segundo lugar, debe cambiar su acción de creación para manejar los datos que obtiene de esa cuadrícula. Puedes tomar ayuda de Batch Insert

Espero eso ayude...