My search is not working in yii2 ,i have to try to find the solution but fails - yii2

I want to search my data but the search is not working. I can't understand what's going wrong? please help to fix it... here is the code
payable controller
<?php
namespace app\controllers;
use Yii;
use app\models\Payable;
use app\models\PayableSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* PayableController implements the CRUD actions for Payable model.
*/
class PayableController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Payable models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new PayableSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Payable model.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Payable model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Payable();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Payable model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
]);
}
/**
* Deletes an existing Payable model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Payable model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Payable the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Payable::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
}
PaybleSearch
<?php
namespace app\models;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Payable;
/**
* PayableSearch represents the model behind the search form of `app\models\Payable`.
*/
class PayableSearch extends Payable
{
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['id', 'consumer_id', 'total_months_conservancy', 'water_arrears', 'conservancy_amount', 'total_water_and_conservancy_amount', 'tinure', 'dues_amount', 'per_month_charges', 'no_of_months', 'total_amount_of_current_months', 'advanced_pay', 'arrears', 'arrears_period', 'total_bill', 'after_due_date_charges', 'total_after_due_date', 'balance_arears', 'water_charges_per_month', 'conservancy_charges_per_month', 'four_months_water_charges', 'four_months_conservancy_charges'], 'integer'],
[['water_remarks', 'remarks', 'billing_months', 'issue_date', 'due_date'], 'safe'],
];
}
/**
* {#inheritdoc}
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = Bill::find()->where('status=0');
// echo"<pre>";
// print_r($query);
// exit();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'consumer_id' => $this->consumer_id,
'total_months_conservancy' => $this->total_months_conservancy,
'water_arrears' => $this->water_arrears,
'conservancy_amount' => $this->conservancy_amount,
'total_water_and_conservancy_amount' => $this->total_water_and_conservancy_amount,
'tinure' => $this->tinure,
'dues_amount' => $this->dues_amount,
'per_month_charges' => $this->per_month_charges,
'no_of_months' => $this->no_of_months,
'total_amount_of_current_months' => $this->total_amount_of_current_months,
'advanced_pay' => $this->advanced_pay,
'arrears' => $this->arrears,
'arrears_period' => $this->arrears_period,
'total_bill' => $this->total_bill,
'after_due_date_charges' => $this->after_due_date_charges,
'total_after_due_date' => $this->total_after_due_date,
'balance_arears' => $this->balance_arears,
'water_charges_per_month' => $this->water_charges_per_month,
'conservancy_charges_per_month' => $this->conservancy_charges_per_month,
'four_months_water_charges' => $this->four_months_water_charges,
'four_months_conservancy_charges' => $this->four_months_conservancy_charges,
'issue_date' => $this->issue_date,
'due_date' => $this->due_date,
]);
$query->andFilterWhere(['like', 'water_remarks', $this->water_remarks])
->andFilterWhere(['like', 'remarks', $this->remarks])
->andFilterWhere(['like', 'billing_months', $this->billing_months]);
return $dataProvider;
}
}
Payable Model
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "payable".
*
* #property int $id
* #property int $consumer_id
* #property int $total_months_conservancy
* #property int $water_arrears
* #property string $water_remarks
* #property int $conservancy_amount
* #property int $total_water_and_conservancy_amount
* #property int $tinure
* #property int $dues_amount
* #property int $per_month_charges
* #property int $no_of_months
* #property int $total_amount_of_current_months
* #property int $advanced_pay
* #property int $arrears
* #property int $arrears_period
* #property int $total_bill
* #property int $after_due_date_charges
* #property int $total_after_due_date
* #property int $balance_arears
* #property string $remarks
* #property int $water_charges_per_month
* #property int $conservancy_charges_per_month
* #property int $four_months_water_charges
* #property int $four_months_conservancy_charges
* #property string $billing_months
* #property string $issue_date
* #property string $due_date
*/
class Payable extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'payable';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['consumer_id', 'total_months_conservancy', 'water_arrears', 'water_remarks', 'conservancy_amount', 'total_water_and_conservancy_amount', 'tinure', 'dues_amount', 'per_month_charges', 'no_of_months', 'total_amount_of_current_months', 'advanced_pay', 'arrears', 'arrears_period', 'total_bill', 'after_due_date_charges', 'total_after_due_date', 'balance_arears', 'remarks', 'water_charges_per_month', 'conservancy_charges_per_month', 'four_months_water_charges', 'four_months_conservancy_charges', 'billing_months', 'issue_date', 'due_date'], 'required'],
[['consumer_id', 'total_months_conservancy', 'water_arrears', 'conservancy_amount', 'total_water_and_conservancy_amount', 'tinure', 'dues_amount', 'per_month_charges', 'no_of_months', 'total_amount_of_current_months', 'advanced_pay', 'arrears', 'arrears_period', 'total_bill', 'after_due_date_charges', 'total_after_due_date', 'balance_arears', 'water_charges_per_month', 'conservancy_charges_per_month', 'four_months_water_charges', 'four_months_conservancy_charges'], 'integer'],
[['issue_date', 'due_date'], 'safe'],
[['water_remarks'], 'string', 'max' => 250],
[['remarks'], 'string', 'max' => 350],
[['billing_months'], 'string', 'max' => 25],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'consumer_id' => 'Consumer ID',
'total_months_conservancy' => 'Total Months Conservancy',
'water_arrears' => 'Water Arrears',
'water_remarks' => 'Water Remarks',
'conservancy_amount' => 'Conservancy Amount',
'total_water_and_conservancy_amount' => 'Total Water And Conservancy Amount',
'tinure' => 'Tinure',
'dues_amount' => 'Dues Amount',
'per_month_charges' => 'Per Month Charges',
'no_of_months' => 'No Of Months',
'total_amount_of_current_months' => 'Total Amount Of Current Months',
'advanced_pay' => 'Advanced Pay',
'arrears' => 'Arrears',
'arrears_period' => 'Arrears Period',
'total_bill' => 'Total Bill',
'after_due_date_charges' => 'After Due Date Charges',
'total_after_due_date' => 'Total After Due Date',
'balance_arears' => 'Balance Arears',
'remarks' => 'Remarks',
'water_charges_per_month' => 'Water Charges Per Month',
'conservancy_charges_per_month' => 'Conservancy Charges Per Month',
'four_months_water_charges' => 'Four Months Water Charges',
'four_months_conservancy_charges' => 'Four Months Conservancy Charges',
'billing_months' => 'Billing Months',
'issue_date' => 'Issue Date',
'due_date' => 'Due Date',
];
}
public function getconsumerId()
{
return $this->hasOne(Plot::className(),['id' => 'consumer_id']);
}
}
View.php
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* #var $this yii\web\View */
/* #var $model app\models\Payable */
$this->title = $model->id;
$this->params['breadcrumbs'][] = ['label' => 'Payables', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
\yii\web\YiiAsset::register($this);
?>
<div class="payable-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'consumer_id',
'total_months_conservancy',
'water_arrears',
'water_remarks',
'conservancy_amount',
'total_water_and_conservancy_amount',
'tinure',
'dues_amount',
'per_month_charges',
'no_of_months',
'total_amount_of_current_months',
'advanced_pay',
'arrears',
'arrears_period',
'total_bill',
'after_due_date_charges',
'total_after_due_date',
'balance_arears',
'remarks',
'water_charges_per_month',
'conservancy_charges_per_month',
'four_months_water_charges',
'four_months_conservancy_charges',
'billing_months',
'issue_date',
'due_date',
],
]) ?>
</div>
Index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel app\models\PayableSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Payables';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="payable-index">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Create Payable', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//
'id',
[ 'header'=> 'Consumer Name',
'attribute'=>'consumer_id',
'value'=>'consumerId.allottee_name',
],
// 'total_months_conservancy',
// 'water_arrears',
// 'water_remarks',
// 'conservancy_amount',
//'total_water_and_conservancy_amount',
//'tinure',
//'dues_amount',
//'per_month_charges',
//'no_of_months',
//'total_amount_of_current_months',
//'advanced_pay',
'arrears',
//'arrears_period',
'total_bill',
//'after_due_date_charges',
'total_after_due_date',
//'balance_arears',
//'remarks',
//'water_charges_per_month',
//'conservancy_charges_per_month',
//'four_months_water_charges',
//'four_months_conservancy_charges',
'billing_months',
//'issue_date',
'due_date',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
I want to make a search but the search is not working. I tried but fails. I could not found any error.please help me in finding the issue

Related

I'm a yii2 developer i want to change the color of string

I want to change the color of the return value I want 'paid' with green background and 'pending'enter image description here with red, I'm trying to change the color but I did not. I will attach the code and a screenshot below. Kindly tell me the solution to solve this issue.Im trying but failed
View
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\helpers\Url;
use yii\widgets\pjax;
/* #var $this yii\web\View */
/* #var $searchModel app\models\BillSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Bills';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="bill-index">
<?php echo $this->render('_search', ['model' => $searchModel]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'id',
[ 'header'=> 'Name',
'attribute'=>'consumer_id',
'value'=>'consumerId.allottee_name',
],
'cnic',
'fileNo.file_no',
'total_bill',
[
'header' => 'Status',
'attribute' => 'status',
'value' => function ($model, $widget) {
if($model->status == 1){
return ("Paid");
} else{
return ("Pending");
}
},
],
],
]); ?>
</div>
Model
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "bill".
*
* #property int $id
* #property int $consumer_id
* #property int $total_months_conservancy
* #property int $water_arrears
* #property string $water_remarks
* #property int $conservancy_amount
* #property int $total_water_and_conservancy_amount
* #property int $tinure
* #property int $dues_amount
* #property int $per_month_charges
* #property int $no_of_months
* #property int $total_amount_of_current_months
* #property int $advanced_pay
* #property int $arrears
* #property int $water_bill
* #property int $arrears_period
* #property int $total_bill
* #property int $after_due_date_charges
* #property int $total_after_due_date
* #property int $balance_arears
* #property string $remarks
* #property int $conservancy_charges_per_month
* #property string $billing_months
* #property string $issue_date
* #property string $due_date
* #property string $cnic
* #property string $reference_no
*/
class Bill extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public $file;
public $file_no;
public static function tableName()
{
return 'bill';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['consumer_id','file_no', 'water_arrears', 'conservancy_amount', 'dues_amount', 'arrears', 'arrears_period', 'total_bill', 'after_due_date_charges', 'total_after_due_date', 'issue_date', 'due_date','status'], 'required'],
[['file'],'file'],
[['consumer_id', 'total_months_conservancy', 'water_arrears', 'conservancy_amount', 'total_water_and_conservancy_amount', 'tinure', 'dues_amount', 'per_month_charges', 'no_of_months', 'total_amount_of_current_months', 'advanced_pay', 'arrears', 'arrears_period', 'total_bill', 'after_due_date_charges', 'total_after_due_date', 'balance_arears','payment','debit','sector'], 'integer'],
[['issue_date', 'water_bill', 'due_date','created_on','updated_on', 'advanced_pay', 'tinure','billing_months','email','cnic','cat_status'], 'safe'],
[['water_remarks','document'], 'string', 'max' => 250],
[['remarks'], 'string', 'max' => 350],
[['billing_months'], 'string', 'max' => 25],
[['reference_no'], 'string', 'max' => 13],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'Bill No',
'consumer_id' => 'Name',
'cnic'=>'CNIC',
'email'=>'Email',
'total_months_conservancy' => 'Total Months Conservancy',
'water_arrears' => 'Water Arrears',
'water_remarks' => 'Water Remarks',
'conservancy_amount' => 'Conservancy Amount',
'total_water_and_conservancy_amount' => 'Total Water And Conservancy Amount',
'tinure' => 'Tinure',
'sector' => 'Sector',
'dues_amount' => 'Dues Amount',
'per_month_charges' => 'Per Month Charges',
'no_of_months' => 'No Of Months',
'total_amount_of_current_months' => 'Total Amount Of Current Months',
'advanced_pay' => 'Advanced Pay',
'debit' => 'debit Pay',
'arrears' => 'Arrears',
'water_bill' => 'water_bill',
'arrears_period' => 'Arrears Period',
'total_bill' => 'Total Bill',
'Status'=>'Status',
'after_due_date_charges' => 'After Due Date Charges',
'total_after_due_date' => 'Total After Due Date',
'balance_arears' => 'Balance Arears',
'remarks' => 'Remarks',
'conservancy_charges_per_month' => 'Conservancy Charges Per Month',
'billing_months' => 'Tenure',
'issue_date' => 'Issue Date',
'due_date' => 'Due Date',
'reference_no' => 'Reference No',
'cat_status'=> 'Status',
];
}
public function getconsumerId()
{
return $this->hasOne(Plot::className(),['id' => 'consumer_id']);
}
public function getfileNo()
{
return $this->hasOne(Plot::className(),['id' => 'consumer_id']);
}
public function getsectorName()
{
return $this->hasOne(Sectors::className(),['id' => 'sector']);
}
}
Use rowOptions https://www.yiiframework.com/doc/api/2.0/yii-grid-gridview#$rowOptions-detail to provide html attributes on a per row basis.
<?= \yii\grid\GridView::widget([
// ...
'rowOptions' => function($model, $key, $index, $grid) {
return ['class' => $model->status === 1 ? 'table-success' : 'table-danger'];
},
// ...
]); ?>
Better to make function in model for this kind of code. I am guessing that you are using bootstrap.
'header' => 'Status',
'attribute' => 'status',
'value' => function ($model, $widget) {
if($model->status == 1){
return "<span class=\"badge badge-success\">Paid</span>";
} else{
return "<span class=\"badge badge-danger\">Pending</span>";
}
},
'format' => 'raw', //'format' => 'html',

yii2 - get name instead of id from database

Sorry im newbie for framework
i've seen many tutorials from Doingiteasy youtube channel and stuck in this
i want an example to change the id_status to become 'infostatus'.
i heard in the videos, to change id to name, i have to use relation. where can i find that?
this is my view index
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel app\models\ReservasiSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Reservasis';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="reservasi-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Reservasi', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id_reservasi',
'id_paket',
**'id_status',**
'id_jadwal',
'id',
// 'tanggalreservasi',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
this is my model from reservasi
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "reservasi".
*
* #property string $id_reservasi
* #property string $id_paket
* #property integer $id_status
* #property string $id_jadwal
* #property string $id
* #property string $tanggalreservasi
*
* #property User $id0
* #property Jadwal $idJadwal
* #property Paket $idPaket
* #property Status $idStatus
*/
class Reservasi extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'reservasi';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['id_reservasi', 'tanggalreservasi'], 'required'],
[['id_status'], 'integer'],
[['tanggalreservasi'], 'safe'],
[['id_reservasi'], 'string', 'max' => 15],
[['id_paket'], 'string', 'max' => 5],
[['id_jadwal'], 'string', 'max' => 4],
[['id'], 'string', 'max' => 6],
[['id'], 'exist', 'skipOnError' => true, 'targetClass' => Users::className(), 'targetAttribute' => ['id' => 'id']],
[['id_jadwal'], 'exist', 'skipOnError' => true, 'targetClass' => Jadwal::className(), 'targetAttribute' => ['id_jadwal' => 'id_jadwal']],
[['id_paket'], 'exist', 'skipOnError' => true, 'targetClass' => Paket::className(), 'targetAttribute' => ['id_paket' => 'id_paket']],
[['id_status'], 'exist', 'skipOnError' => true, 'targetClass' => Status::className(), 'targetAttribute' => ['id_status' => 'id_status']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id_reservasi' => 'Id Reservasi',
'id_paket' => 'Id Paket',
'id_status' => 'Id Status',
'id_jadwal' => 'Id Jadwal',
'id' => 'ID',
'tanggalreservasi' => 'Tanggalreservasi',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getId0()
{
return $this->hasOne(Users::className(), ['id' => 'id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getIdJadwal()
{
return $this->hasOne(Jadwal::className(), ['id_jadwal' => 'id_jadwal']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getIdPaket()
{
return $this->hasOne(Paket::className(), ['id_paket' => 'id_paket']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getIdStatus()
{
return $this->hasOne(Status::className(), ['id_status' => 'id_status']);
}
}
and this is from model Status
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "status".
*
* #property integer $id_status
* #property string $infostatus
*
* #property Reservasi[] $reservasis
*/
class Status extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'status';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['id_status'], 'required'],
[['id_status'], 'integer'],
[['infostatus'], 'string', 'max' => 20],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id_status' => 'Id Status',
'infostatus' => 'Infostatus',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getReservasis()
{
return $this->hasMany(Reservasi::className(), ['id_status' => 'id_status']);
}
}
you could add a relation to your Reservasi model for get the infostatus
Assuming you have a model named Status that contain the fields id and infostatus
/* ActiveRelation */
public function getInfostatus()
{
return $this->hasOne(Status::className(), ['id' => 'id_status']);
}
then you could refer to
$model->infostatus; // for get the value

Insert checked rows from a gridview to a table in yii2

With reference to Insert multiple rows into table by checkboxcolumn in yii2 I'm asking this question. I'm trying to insert data into rawmaterial table. The data that will be inserted is coming from rmtemplate table. I've added a gridview that loads data from rmtemplate in the rawmaterial form. Along with the checked rows I have two more fields usedate, chargenumber which will be inserted with each row.
Bythe code below it only inserts a single row with no other data except 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 model
<?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 model
<?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',
];
}
}
Rawmaterial controller
<?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;
}
}
The debug toolbar shows the following -
After moving save function to RawmaterialForm model
VarDump
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 in Function
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;
}
function saveRawTemlate
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;
}
Output
Controller
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,
]);
}
Model
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;
}

Insert multiple rows into table by checkboxcolumn in yii2

I have a table rawmaterial. The fields are - rmname, usedate, useqty, unitcost, productname, chargenumber. I've added a gridview (which comes from rmtemplate table) with a checkboxcolumn in the form. The gridview contains columns productname, rmname, qty, unitcost. How can I insert the checked rows along with usedate, chargenumber(which come from respective textboxes) in the table rawmaterial.
I've checked ActiveRecord batch insert (yii2) but not getting how to use it with checkbocolumn.
Checked How I can process a checkbox column from Yii2 gridview? - not quite sure with it.
Checked Yii2 How to properly create checkbox column in gridview for bulk actions? - I think it's not using 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 */
?>
And it looks like below.
CreateAction looks like -
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,
]);
}
}
Update
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
According to my understanding, you have to do two things.
Firstly, you have to grab all the checked rows data of the grid view as an array or object. You can see how to do that from Get Grid Data .
Secondly you have to change your create action for handling the data you fetch from that grid. You can take help from Batch Insert
Hope it helps...
Prepare additional model like RawMaterialForm with properties that will be taken from ActiveForm usedate, chargenumber and rmtemplate_ids. The last one is the array of GridView IDs. Remember to add rules() in the RawMaterialForm for the properties.
The view - just the GridView needs some tweaks. Extend the configuration for Checkbox column.
[
'class' => 'kartik\grid\CheckboxColumn',
'name' => 'RawMaterialForm[rmtemplate_ids]',
'checkboxOptions' => function ($model, $key, $index, $column) {
return ['value' => $model->id];
}
],
The action:
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's save() method:
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;
}
This will copy every selected row into a new Rawmaterial row with additional inputs from ActiveForm.
In case of errors in $rawMaterial saving check $rawMaterial->errors property.
Fair warning - depending on the system performance this can be slow (or even fatal) in case of selecting many rows at once.

Data is not populating in second level kartik depDrop in yii2. Gettin 0,1,2,3,4

When I'm selecting First Category - I can see the data in firebug that should populate in the secon level but it's instead populating 0,1,2,3,4 and I'm unable to select it.
My _form is
<?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
use yii\web\View;
use frontend\assets\XyzAsset;
use yii\helpers\ArrayHelper;
use dosamigos\datepicker\DatePicker;
use kartik\select2\Select2;
use frontend\modules\production\models\Productbatch;
use frontend\modules\production\models\Productnames;
use kartik\depdrop\DepDrop;
use yii\helpers\Json;
//XyzAsset::register($this);
/* #var $this yii\web\View */
/* #var $model frontend\modules\production\models\Production */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="production-form">
<?php $form = ActiveForm::begin(); ?>
<!--<?= Html::a('Select Product', ['/production/productbatch/index'], ['class'=>'btn btn-primary']) ?> -->
<?= $form->field($model, 'productiondate')->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,
'format' => 'yyyy-mm-dd'
]
]);?>
<!-- echo CHtml::button("(+)",array('title'=>"Select Product",'onclick'=>'js:selectproductforproduction();')); -->
<?= $form->field($model, 'productname')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Productnames::find()->all(),'productnames_productname','productnames_productname'),
'language' => 'en',
'options' => ['placeholder' => 'Select Product Name', 'id' => 'cat-id'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?= $form->field($model, 'batchno')->widget(DepDrop::classname(), [
'options'=>['id'=>'subcat-id'],
'pluginOptions'=>[
'depends'=>['cat-id'],
'placeholder'=>'Select BatchNo',
'url'=>Url::to(['/production/productbatch/subcat'])
]
]); ?>
<?= $form->field($model, 'prodqty')->textInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Controller -
<?php
namespace frontend\modules\production\controllers;
use Yii;
use frontend\modules\production\models\Productbatch;
use frontend\modules\production\models\ProductbatchSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Json;
/**
* ProductbatchController implements the CRUD actions for Productbatch model.
*/
class ProductbatchController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
/**
* Lists all Productbatch models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new ProductbatchSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Productbatch model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Productbatch model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Productbatch();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->itemid]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Productbatch 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->itemid]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Productbatch 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 actionSubcat() {
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$cat_id = $parents[0];
$out = Productbatch::getBatchNo($cat_id);
// the getSubCatList function will query the database based on the
// cat_id and return an array like below:
// [
// ['id'=>'<sub-cat-id-1>', 'name'=>'<sub-cat-name1>'],
// ['id'=>'<sub-cat_id_2>', 'name'=>'<sub-cat-name2>']
// ]
echo Json::encode(['output'=>$out, 'selected'=>'']);
return;
}
}
echo Json::encode(['output'=>'', 'selected'=>'']);
}
/**
* Finds the Productbatch model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Productbatch the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Productbatch::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
Model
<?php
namespace frontend\modules\production\models;
use Yii;
/**
* This is the model class for table "productbatch".
*
* #property integer $itemid
* #property string $productname
* #property string $batchno
* #property string $mfgdate
* #property string $expdate
* #property double $mrp
* #property double $rate
*
* #property Productnames $productname0
*/
class Productbatch extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'productbatch';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['batchno'], 'string'],
[['mfgdate', 'expdate'], 'safe'],
[['mrp', 'rate'], 'number'],
[['productname'], 'string', 'max' => 25]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'itemid' => 'Itemid',
'productname' => 'Productname',
'batchno' => 'Batchno',
'mfgdate' => 'Mfgdate',
'expdate' => 'Expdate',
'mrp' => 'Mrp',
'rate' => 'Rate',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getProductname0()
{
return $this->hasOne(Productnames::className(), ['productnames_productname' => 'productname']);
}
public static function getBatchNo($cat_id)
{
$data = static::find()->where(['productname'=>$cat_id])->select(['batchno'])->asArray()->all();
$value = (count($data) == 0) ? ['' => ''] : $data;
return $value;
}
}
The output looks like -