Pass data from a form to a controller in yii2 - yii2

I am creating a page that has 3 fields - product code, startdate, enddate. When I click on the search button it should create a pdf file. 3 of these fields are without model.
I've tried code -
<?php
use yii\helpers\Html;
//use yii\grid\GridView;
use kartik\grid\GridView;
use kartik\export\ExportMenu;
use frontend\modules\stock\models\Sellitem;
use dosamigos\datepicker\DatePicker;
use dosamigos\datepicker\DateRangePicker;
use kartik\form\ActiveForm;
/* #var $this yii\web\View */
/* #var $searchModel frontend\modules\stock\models\SellitemSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Stock';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="sellitem-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<div class="row">
<div class="form-group">
<div class="col-xs-4 col-sm-4 col-lg-4">
<label for="upc" class="control-label"><p class="text-info">Product Code <i class="icon-star"></i></p></label>
<input type="text" class="form-control" id="upc" class="span3">
</div>
<div class="col-xs-4 col-sm-4 col-lg-4">
<label for="upc" class="control-label"><p class="text-info">Start Date <i class="icon-star"></i></p></label>
<?= DatePicker::widget([
//'label' => 'Startdate',
'name' => 'startdate',
'id' => 'startdate',
//'value' => '02-16-2012',
'template' => '{addon}{input}',
'clientOptions' => [
'autoclose' => true,
'todayHighlight' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
<div class="col-xs-4 col-sm-4 col-lg-4">
<label for="upc" class="control-label"><p class="text-info">End Date <i class="icon-star"></i></p></label>
<?= DatePicker::widget([
//'label' => 'Startdate',
'name' => 'enddate',
'id' => 'enddate',
//'value' => '02-16-2012',
'template' => '{addon}{input}',
'clientOptions' => [
'autoclose' => true,
'todayHighlight' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
</div>
</div>
<p>
<div class="form-group pull-right">
<?= Html::a('Search', ['/stock/sellitem/stockbetweendates','upc'=> $upc, 'startdate'=> $startdate, 'enddate'=>$enddate],
['class'=>'btn btn-success'])
?>
</div>
</p>
</div>
This is giving error - undefined variable.
I've added $upc, $startdate, $enddate in the model but it's not helping. Please let me know what to do to pass these values to controller.
Controller Action
public function actionStockbetweendates($upc, $startdate, $enddate) {
$upc = yii::$app->request->get('upc');
$startdate = yii::$app->request->get('startdate');
$enddate = yii::$app->request->get('enddate');
// $modelProduction = Puritem::find()->where(['pi_upc' => $productname]);
// $searchModel1 = new PuritemsbSearch();
// $dataProvider1 = $searchModel1->search(Yii::$app->request->queryParams, $productname);
// $modelSell = Sellitem::find()->where(['si_iupc' => $productname]);
// $searchModel2 = new SellitemsbSearch();
// $dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams, $productname);
// $content = $this->renderPartial('_printproductledger', [
// 'modelProduction' => $modelProduction,
// 'dataProvider1' => $dataProvider1,
// 'searchModel1' => $searchModel1,
// //'data'=> $data,
// 'modelSell' => $modelSell,
// 'searchModel2' => $searchModel2,
// 'dataProvider2' => $dataProvider2,
// 'productname' => $productname,
// 'prodesc' => $prodesc,
// ]);
// $footer = "<table name='footer' width=\"1000\">
// <tr>
// <td style='font-size: 18px; padding-bottom: 20px;' align=\"right\">Signature</td>
// </tr>
// </table>";
// $pdf = new Pdf([
// 'mode'=> Pdf::MODE_UTF8,
// 'format'=> Pdf::FORMAT_A4,
// 'destination'=> Pdf::DEST_BROWSER,
// 'orientation'=> Pdf::ORIENT_LANDSCAPE,
// //'destination' => Pdf::DEST_DOWNLOAD,
// 'cssFile' => '#vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
// // any css to be embedded if required
// 'cssInline' => '.kv-heading-1{font-size:18px}',
// // set mPDF properties on the fly
// 'options' => ['title' => 'Print Party Ledger'],
// //'options' => ['defaultfooterline' => 0,],
// 'options' => ['defaultheaderline' => 0,],
// // call mPDF methods on the fly
// 'methods' => [
// 'SetHeader'=>['Ledger'],
// //'SetFooter'=>[$footer],
// ],
// 'content' => $content,
// ]);
// return $pdf->render();
//return $this->render('_printSalarystatement', ['s_period' => $s_period]);
}
ActionIndex that renders to the index2 page
public function actionIndex2()
{
$searchModel = new SellitemSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index2', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}

I'm not sure how it works without rendering... But anyway, to make them defined, you need to pass them to view file. The most common method (and I think the best by far) is to use $this->render() operation. At the end of of your public function actionStockbetweendates($upc, $startdate, $enddate) { add this:
return $this->render('index2', [
'upc' => $upc,
'startdate' => $startdate,
'enddate' => $enddate,
];
One side note: you don't need to use these:
$upc = yii::$app->request->get('upc');
$startdate = yii::$app->request->get('startdate');
$enddate = yii::$app->request->get('enddate');
They are already defined (used) in parameters.

Related

Generate pdf by controller action when data is passed through javascript in yii2

This is the continuation of question Pass data from a form to a controller in yii2 and Get data from textbox and pass to Controller in yii2.
I'm trying to generate a report by controllerAction actionStockbetweendates. The parameters for this productname, startdate, enddate comes from index2 through a javascript function on clicking of a button. In console I'm getting the following error.
index2.php
<?php
use yii\helpers\Html;
//use yii\grid\GridView;
use kartik\grid\GridView;
use kartik\export\ExportMenu;
use frontend\modules\stock\models\Sellitem;
use dosamigos\datepicker\DatePicker;
use dosamigos\datepicker\DateRangePicker;
use kartik\form\ActiveForm;
use yii\helpers\Json;
use yii\db\Query;
use yii\db\Command;
use kartik\mpdf\Pdf;
/* #var $this yii\web\View */
/* #var $searchModel frontend\modules\stock\models\SellitemSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Stock';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="sellitem-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<div class="row">
<div class="form-group">
<div class="col-xs-4 col-sm-4 col-lg-4">
<label for="upc" class="control-label"><p class="text-info">Product Code <i class="icon-star"></i></p></label>
<input type="text" class="form-control" id="upc" class="span3">
</div>
<div class="col-xs-4 col-sm-4 col-lg-4">
<label for="upc" class="control-label"><p class="text-info">Start Date <i class="icon-star"></i></p></label>
<?= DatePicker::widget([
//'label' => 'Startdate',
'name' => 'startdate',
'id' => 'startdate',
//'value' => '02-16-2012',
'template' => '{addon}{input}',
'clientOptions' => [
'autoclose' => true,
'todayHighlight' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
<div class="col-xs-4 col-sm-4 col-lg-4">
<label for="upc" class="control-label"><p class="text-info">End Date <i class="icon-star"></i></p></label>
<?= DatePicker::widget([
//'label' => 'Startdate',
'name' => 'enddate',
'id' => 'enddate',
//'value' => '02-16-2012',
'template' => '{addon}{input}',
'clientOptions' => [
'autoclose' => true,
'todayHighlight' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
</div>
</div>
<p>
<div class="form-group pull-right">
<button id="yourButton" class="btn btn-primary" >Seach</button>
</div>
</p>
</div>
<?php
/* start getting the itemid */
$this->registerJs(
"$('#yourButton').on('click', function() {
var productname = $('#upc').val();
var startdate = $('#startdate').val();
var enddate = $('#enddate').val();
//alert(uPc);
$.get('index.php?r=stock/sellitem/stockbetweendates',{ productname : productname, startdate : startdate, enddate : enddate}, function(data){
var data = $.parseJSON(data);
});
});"
);
/* end getting the itemid */
?>
ControllerAction
public function actionStockbetweendates($productname, $startdate, $enddate) {
$modelProduction = Puritem::find()->where(['pi_upc' => $productname]);
$searchModel1 = new PuritemsbSearch();
$dataProvider1 = $searchModel1->search(Yii::$app->request->queryParams, $productname);
$modelSell = Sellitem::find()->where(['si_iupc' => $productname]);
$searchModel2 = new SellitemsbSearch();
$dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams, $productname);
$content = $this->renderPartial('_printproductledgerbtdt', [
'modelProduction' => $modelProduction,
'dataProvider1' => $dataProvider1,
'searchModel1' => $searchModel1,
//'data'=> $data,
'modelSell' => $modelSell,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
'productname' => $productname,
//'prodesc' => $prodesc,
]);
$footer = "<table name='footer' width=\"1000\">
<tr>
<td style='font-size: 18px; padding-bottom: 20px;' align=\"right\">Signature</td>
</tr>
</table>";
$pdf = new Pdf([
'mode'=> Pdf::MODE_UTF8,
'format'=> Pdf::FORMAT_A4,
'destination'=> Pdf::DEST_BROWSER,
'orientation'=> Pdf::ORIENT_LANDSCAPE,
//'destination' => Pdf::DEST_DOWNLOAD,
'cssFile' => '#vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
// any css to be embedded if required
'cssInline' => '.kv-heading-1{font-size:18px}',
// set mPDF properties on the fly
'options' => ['title' => 'Print Party Ledger'],
//'options' => ['defaultfooterline' => 0,],
'options' => ['defaultheaderline' => 0,],
// call mPDF methods on the fly
'methods' => [
'SetHeader'=>['Ledger'],
//'SetFooter'=>[$footer],
],
'content' => $content,
]);
return $pdf->render();
//return $this->render('_printSalarystatement', ['s_period' => $s_period]);
return $this->render('index2', [
'upc' => $upc,
'startdate' => $startdate,
'enddate' => $enddate,
]);
}
updated javascript
<?php
/* start getting the itemid */
$this->registerJs(
"$('#yourButton').on('click', function() {
var productname = $('#upc').val();
var startdate = $('#startdate').val();
var enddate = $('#enddate').val();
//alert(uPc);
$.get('index.php?r=stock/sellitem/stockbetweendates',{ productname : productname, startdate : startdate, enddate : enddate});
});"
);
/* end getting the itemid */
?>
Updated Controller Action
public function actionStockbetweendates($productname, $startdate, $enddate) {
$modelProduction = Puritem::find()->where(['pi_upc' => $productname]);
$searchModel1 = new PuritemsbSearch();
$dataProvider1 = $searchModel1->search(Yii::$app->request->queryParams, $productname);
$modelSell = Sellitem::find()->where(['si_iupc' => $productname]);
$searchModel2 = new SellitemsbSearch();
$dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams, $productname);
$content = $this->renderPartial('_printproductledgerbtdt', [
'modelProduction' => $modelProduction,
'dataProvider1' => $dataProvider1,
'searchModel1' => $searchModel1,
//'data'=> $data,
'modelSell' => $modelSell,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
'productname' => $productname,
//'prodesc' => $prodesc,
]);
$footer = "<table name='footer' width=\"1000\">
<tr>
<td style='font-size: 18px; padding-bottom: 20px;' align=\"right\">Signature</td>
</tr>
</table>";
$pdf = new Pdf([
'mode'=> Pdf::MODE_UTF8,
'format'=> Pdf::FORMAT_A4,
'destination'=> Pdf::DEST_BROWSER,
'orientation'=> Pdf::ORIENT_LANDSCAPE,
//'destination' => Pdf::DEST_DOWNLOAD,
'cssFile' => '#vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
// any css to be embedded if required
'cssInline' => '.kv-heading-1{font-size:18px}',
// set mPDF properties on the fly
'options' => ['title' => 'Print Party Ledger'],
//'options' => ['defaultfooterline' => 0,],
'options' => ['defaultheaderline' => 0,],
// call mPDF methods on the fly
'methods' => [
'SetHeader'=>['Ledger'],
//'SetFooter'=>[$footer],
],
'content' => $content,
]);
return $pdf->render();
}
Output
Earlier used button to call Controller action and passing parameter
[
'class' => 'kartik\grid\ActionColumn',
'template' => '{ledger}',
'buttons' => [
'ledger' => function ($url, $model) {
//var_dump($model);
//exit;
return Html::a(
'<span class="glyphicon glyphicon-eye-open"></span>',
['/stock/sellitem/printproductledger', 'productname' => $model['i_upc'],'prodesc'=>$model['i_desc']],
[
'title' => 'Ledger',
'data-pjax' => '0',
]
);
},
],
],
Updated Controller Action
public function actionPrintproductledger2($productname) {
$productname = yii::$app->request->get('productname');
$prodesc = yii::$app->request->get('prodesc');
$modelProduction = Puritem::find()->where(['pi_upc' => $productname]);
$searchModel1 = new PuritemsbSearch();
$dataProvider1 = $searchModel1->search(Yii::$app->request->queryParams, $productname);
$modelSell = Sellitem::find()->where(['si_iupc' => $productname]);
$searchModel2 = new SellitemsbSearch();
$dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams, $productname);
Yii::$app->response->format = Response::FORMAT_JSON;
return $this->render('_printproductledgerbtdt', [
'modelProduction' => $modelProduction,
'modelSell' => $modelSell,
'dataProvider1' => $dataProvider1,
'searchModel1' => $searchModel1,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
'productname' => $productname,
'prodesc' => $prodesc,
]);
}
updated javascript
<?php
/* start getting the itemid */
$this->registerJs(
"$('#yourButton').on('click', function() {
var productname = $('#upc').val();
var startdate = $('#startdate').val();
var enddate = $('#enddate').val();
var desc = $('#desc').val();
//alert(productname);
//$.get('index.php?r=stock/sellitem/printproductledger2',{ productname : productname, startdate : startdate, enddate : enddate,prodesc:desc});
$.ajax({
type: 'GET',
url: 'index.php?r=stock/sellitem/printproductledger2',
data: { productname:productname, startdate : startdate, enddate : enddate,prodesc:desc},
contentType: 'application/json; charset=utf-8',
//dataType: 'json',
success: function() { alert('Success'); }
});
});"
);
/* end getting the itemid */
?>
You code can't work for several reason
so this is not properly an answer but some main suggetions
1) you are using this call for obtain data
$.get('index.php?r=stock/sellitem/stockbetweendates',
{ productname : productname, startdate : startdate, enddate : enddate},
function(data){
var data = $.parseJSON(data);
});
the data obtain are not correctly JSON formatted ..
If you need correct data JSON format you should encode_JSON properly in you action and send this data to the caller using an echo.
2 ) In you actionStockbetweendates
you have two time the return statement
]);
return $pdf->render();
//return $this->render('_printSalarystatement', ['s_period' => $s_period]);
return $this->render('index2', [
'upc' => $upc,
'startdate' => $startdate,
'enddate' => $enddate,
]);
obviously only the firts work .. and (could be) render a pdf ..
but in this way yuo are not sending nothings to the ajax caller ($.get...)
My suggestion is that you split you code in separated function .. each of this specifically related to a single need .
And for pdf try using
'mode' => Pdf::MODE_BLANK,
instead of ( 'mode'=> Pdf::MODE_UTF8,)

Get data from select2 and pass it to controller in yii2

I've one select2 form field, two datepickers and a search button in productnames index file. It is only to search data I'm unable to get the data selected in the select2 widget and pass it to controller which in turn can search other models.
index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use kartik\select2\Select2;
use dosamigos\datepicker\DatePicker;
use yii\helpers\ArrayHelper;
use frontend\modules\sbbtdtproduct\models\Productnames;
use yii\helpers\Json;
/* #var $this yii\web\View */
/* #var $searchModel frontend\modules\sbbtdtproduct\models\ProductnamesSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Productnames';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="productnames-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<div class="row">
<div class="form-group">
<div class="col-xs-5 col-sm-5 col-lg-5" >
<?php
echo Select2::widget([
'model' => $model,
'attribute' => 'productnames_productname',
'data' => ArrayHelper::map(Productnames::find()->all(),'productnames_productname','productnames_productname'),
'options' => ['placeholder' => 'Select Product'],
'pluginOptions' => [
'allowClear' => true
],
//'productname' => $productname,
]);
?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= DatePicker::widget([
'name' => 'Start Date',
'attribute' => 'from_date',
'value' => '2014-01-31',
'template' => '{addon}{input}',
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= DatePicker::widget([
'name' => 'End Date',
'attribute' => 'to_date',
'value' => '2014-01-31',
'template' => '{addon}{input}',
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
<div class="col-xs-1 col-sm-1 col-lg-1" >
<?= Html::a('Search', ['/sbbtdtproduct/production/index','productname' => $model['productnames_productname']], ['class'=>'btn btn-primary']) ?>
</div>
</div>
</div>
</div>
production controller action
public function actionIndex($productname)
{
$productname = yii::$app->request->get('productnames_productname');
$searchModel = new ProductionSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams, $productname);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
productionsearch model
public function search($params,$productname)
{
$query = Production::find()
->where(['productname' => $productname]);
// 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([
'productionid' => $this->productionid,
'productiondate' => $this->productiondate,
'itemid' => $this->itemid,
'prodqty' => $this->prodqty,
]);
$query->andFilterWhere(['like', 'productname', $this->productname])
->andFilterWhere(['like', 'batchno', $this->batchno]);
return $dataProvider;
}
error -
update -
Database Log
The data base Log shows that no value has been passed from search model.
I can see the value selected in select2 or datepicker as below, but it's not passing to the controller.
1.on your view page
You have not added form tag, so other parameters will not get posted, you must add everything inside form tag and submit that form, as follows
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use kartik\select2\Select2;
use dosamigos\datepicker\DatePicker;
use yii\helpers\ArrayHelper;
use frontend\modules\sbbtdtproduct\models\Productnames;
use yii\helpers\Json;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $searchModel frontend\modules\sbbtdtproduct\models\ProductnamesSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Productnames';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="productnames-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]);
$form = ActiveForm::begin([
'action' => ['/sbbtdtproduct/production/index'],
'method' => 'post',
'options' => ['data-pjax' => true],
'enableClientValidation' => FALSE
]);
?>
<div class="row">
<div class="form-group">
<div class="col-xs-5 col-sm-5 col-lg-5" >
<?php
echo Select2::widget([
'model' => $model,
'attribute' => 'productnames_productname',
'data' => ArrayHelper::map(Productnames::find()->all(),'productnames_productname','productnames_productname'),
'options' => ['placeholder' => 'Select Product'],
'pluginOptions' => [
'allowClear' => true
],
//'productname' => $productname,
]);
?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= DatePicker::widget([
'name' => 'Start Date',
'attribute' => 'from_date',
'value' => '2014-01-31',
'template' => '{addon}{input}',
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= DatePicker::widget([
'name' => 'End Date',
'attribute' => 'to_date',
'value' => '2014-01-31',
'template' => '{addon}{input}',
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
<div class="col-xs-1 col-sm-1 col-lg-1" >
<?= Html::submitButton('Search', ['class'=>'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
</div>
2.Controller
now inside your controller you can access parametes as follows
public function actionIndex()
{
$productname = Yii::$app->request->post('productnames_productname');
$searchModel = new ProductionSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams, $productname);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}

Object of class yii\db\ActiveQuery could not be converted to string

I'm trying to print data with the help of kartik mPDF. The detailview part is printing without any issue. But I need to print some lines along with the detailview. Now I need to pass data from the model to the view to be printed. I'm trying to do that but not so sure. Currently I'm getting error -
Object of class yii\db\ActiveQuery could not be converted to string
I may be wrong in my approach. But please tell me what correction needs to be done. This is the same question as - How to pass data from model to a view in yii2
Code of Controller Action -
public function actionPrintsalarystatement($id) {
//Yii::app()->params['period'] = $period;
//$s_period = $this->originalperiod;
$period = Salary::find()->select(['s_period'])->where(['s_id' => $id])->asArray();
//$period = Yii::$app->request->post('period');
//$this->period = Salary::find()->select(['s_period'])->where(['s_id' => $id]);
//$period = ArrayHelper::map(Salary::find($id)->select(['s_period'])->asArray()->all(), 's_period', 'period'),
//$model = Salary::find()->where(['s_period' => $period]);
$model = $this->findModel($id);
$searchModel = new SalarySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$data = Salary::findOne($id);
$content = $this->renderPartial('_printSalarystatement', [
'model' => $model,
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
'data'=> $data,
'period' => $period,
]);
$pdf = new Pdf([
'mode'=> Pdf::MODE_UTF8,
'format'=> Pdf::FORMAT_A4,
'destination'=> Pdf::DEST_BROWSER,
//'destination' => Pdf::DEST_DOWNLOAD,
'cssFile' => '#vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
// any css to be embedded if required
'cssInline' => '.kv-heading-1{font-size:18px}',
// set mPDF properties on the fly
'options' => ['title' => 'Print Payslip'],
// call mPDF methods on the fly
'methods' => [
'SetHeader'=>['Private and Confidential'],
'SetFooter'=>['This Payslip is computer generated.'],
],
'content' => $content,
]);
return $pdf->render();
//return $this->render('_printSalarystatement', ['s_period' => $s_period]);
}
Updated view.php
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\web\View;
/* #var $this yii\web\View */
/* #var $model frontend\modules\salary\models\Salary */
//#var $model yii\base\Model
//#var $totaldays any
//$this->title = $model->s_id;
//$this->period = $model->s_period;
$this->params['breadcrumbs'][] = ['label' => 'Salaries', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="salary-view">
<h1><strong><p class="text-center">My Company</p></strong></h1>
<p class="text-center">Pay Slip for the month of <?php $model['s_period'];?> </p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
's_id',
's_date',
's_period',
's_empid',
's_empname',
's_workingdays',
's_leave',
's_holiday',
's_wageperday',
's_totalwage',
's_ovthour',
],
]) ?>
</div>
What I'm trying to do -
Currently I'm getting
Comment the $period object you are creating in controller as follows:
public function actionPrintsalarystatement($id) {
//Yii::app()->params['period'] = $period;
//$s_period = $this->originalperiod;
//$period = Salary::find()->select(['s_period'])->where(['s_id' => $id])->asArray(); <=== Comment this line
//$period = Yii::$app->request->post('period');
//$this->period = Salary::find()->select(['s_period'])->where(['s_id' => $id]);
//$period = ArrayHelper::map(Salary::find($id)->select(['s_period'])->asArray()->all(), 's_period', 'period'),
//$model = Salary::find()->where(['s_period' => $period]);
$model = $this->findModel($id);
$searchModel = new SalarySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$data = Salary::findOne($id);
$content = $this->renderPartial('_printSalarystatement', [
'model' => $model,
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
'data'=> $data,
//'period' => $period, <=== Comment this as well
]);
$pdf = new Pdf([
'mode'=> Pdf::MODE_UTF8,
'format'=> Pdf::FORMAT_A4,
'destination'=> Pdf::DEST_BROWSER,
//'destination' => Pdf::DEST_DOWNLOAD,
'cssFile' => '#vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
// any css to be embedded if required
'cssInline' => '.kv-heading-1{font-size:18px}',
// set mPDF properties on the fly
'options' => ['title' => 'Print Payslip'],
// call mPDF methods on the fly
'methods' => [
'SetHeader'=>['Private and Confidential'],
'SetFooter'=>['This Payslip is computer generated.'],
],
'content' => $content,
]);
return $pdf->render();
//return $this->render('_printSalarystatement', ['s_period' => $s_period]);
}
And in your view do the following:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\web\View;
/* #var $this yii\web\View */
/* #var $model frontend\modules\salary\models\Salary */
//#var $model yii\base\Model
//#var $totaldays any
//$this->title = $model->s_id;
//$this->period = $model->s_period;
$this->params['breadcrumbs'][] = ['label' => 'Salaries', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="salary-view">
<h1><strong><p class="text-center">My Company</p></strong></h1>
<p class="text-center">Pay Slip for the month of <?php echo $model['s_period'];?> </p>
<?php
//Add these lines to see what you get in your $Model object
echo '<pre>'; print_r($model); echo '</pre>'; ?>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
's_id',
's_date',
's_period',
's_empid',
's_empname',
's_workingdays',
's_leave',
's_holiday',
's_wageperday',
's_totalwage',
's_ovthour',
],
]) ?>

Search data by taking input from datepicker in yii2

In this case the sql query in the search model is -
$query = (new Query())
->select (['billdate','billno','bills_partyname','billamount'])
->from('bills')
->where(['between', 'billdate', 'from_date', 'to_date']);
I've added a daterangepicker in the index.php file. The code is -
<?= DatePicker::widget([
'name' => 'from_date',
'value' => '2014-01-01',
'type' => DatePicker::TYPE_RANGE,
'name2' => 'to_date',
'value2' => '2016-01-01',
'pluginOptions' => [
'autoclose'=>true,
'format' => 'yyyy-mm-dd'
]
]);
?>
Controller
public function actionIndex()
{
$searchModel = new PartiesSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Parties model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
index.php looks like
<?php
use yii\helpers\Html;
use kartik\grid\GridView;
use kartik\date\DatePicker;
use kartik\daterange\DateRangePicker;
use kartik\form\ActiveForm;
//use dosamigos\datepicker\DatePicker;
use frontend\modules\districtreport\models\ExpartiesSearch;
/* #var $this yii\web\View */
/* #var $searchModel frontend\modules\districtreport\models\PartiesSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Parties';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="parties-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<!-- <p>
<?= Html::a('Create Parties', ['create'], ['class' => 'btn btn-success']) ?>
</p> -->
<!-- <div class="custom-filter">
Date range:
<input name="start" />
<input name="end" />
</div> -->
<?= '<label class="control-label">Select Date Range</label>'; ?>
<?= DatePicker::widget([
'model' => $searchModel,
'attribute' => 'from_date',
'value' => '2014-01-01',
'type' => DatePicker::TYPE_RANGE,
'attribute2' => 'to_date',
'value2' => '2016-01-01',
'pluginOptions' => [
'autoclose'=>true,
'format' => 'yyyy-mm-dd'
]
]);
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'export' => false,
'columns' => [
// [
// 'class' => 'kartik\grid\ExpandRowColumn',
// 'value' => function($model, $key, $index, $column){
// return GridView::ROW_COLLAPSED;
// },
// 'detail' => function($model, $key, $index, $column){
// $searchModel = new ExpartiesSearch();
// $searchModel-> parties_district = $model['district'];
// $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
// return Yii::$app->controller->renderPartial('_exparties', [
// 'searchModel' => $searchModel,
// 'dataProvider' => $dataProvider,
// ]);
// },
// ],
// 'district',
// 'sell',
// 'collection',
'billdate',
'billno',
'bills_partyname',
'billamount',
],
]); ?>
</div>
This is not working. Please tell me what needs to be done.
Somthing like this
In View before GridView
<?php
$form = ActiveForm::begin([
'method' => 'get',
'enableClientScript' => false
]);
?>
<?= '<label class="control-label">Select Date Range</label>'; ?>
<?= DatePicker::widget([
'model' => $searchModel,
'attribute' => 'from_date',
'value' => '2014-01-01',
'type' => DatePicker::TYPE_RANGE,
'attribute2' => 'to_date',
'value2' => '2016-01-01',
'pluginOptions' => [
'autoclose'=>true,
'format' => 'yyyy-mm-dd'
]
]);
?>
<?php echo Html::submitButton('Search') ?>
<?php ActiveForm::end(); ?>
In Controller
public function actionIndex(){
$searchModel = new PartiesSearch();
$dataProvider = $searchModel->search(\Yii::$app->request->get());
return $this->render('index', compact('dataProvider', 'searchModel'));
}
In Your Search Model
class PartiesSearch extends Parties
{
public $from_date;
public $to_date;
//add rule
public function rules(){
return [
//... your rules,
[['from_date', 'to_date'], 'safe']
];
}
//... some code
public function search($params = []){
$query = (new Query())
->select (['billdate','billno','bills_partyname','billamount'])
->from('bills');
$dataProvider = new ActiveDataProvider([
'query' => $query
]);
if( !($this->load($params) && $this->validate()) ){
return $dataProvider;
}
if($this->from_date && $this->to_date)
$query->where(['between', 'billdate', $this->from_date, $this->to_date]);
return $dataProvider;
}
from_date is come by post/Get method Try this
$query = (new Query())->select (['billdate','billno','bills_partyname','billamount'])->from('bills')->where(['between', 'billdate', $_POST['from_date'], $_POST['to_date']]);
You are not using model to create date range picker so either use model or change name from
'name' => 'from_date'
to
'name' => 'PartiesSearch[from_date]'
*and similar for to_date

Yii2 dynamic form (File upload)

I want to use dynamic form in yii2(http://wbraganca.com/yii2extensions) here is my code:
part of controller:
public function actionUpdate($id)
{
$model = $this->findModel($id);
$modelsProductImage = $model->images;
if ($model->load(Yii::$app->request->post())) {
$oldIDs = ArrayHelper::map($modelsProductImage, 'id', 'id');
$modelsProductImage = Model::createMultiple(ProductImage::classname(), $modelsProductImage);
Model::loadMultiple($modelsProductImage, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsProductImage, 'id', 'id')));
foreach ($modelsProductImage as $index => $modelProductImage) {
$modelProductImage->sort_order = $index;
$modelProductImage->product_id = $model->id;
//echo $modelProductImage->file = UploadedFile::getInstance($modelProductImage, "[{$index}]file");
$file = UploadedFile::getInstanceByName($index);
print_r($file);
}
}
}
and this is my view file:
<?php $form = ActiveForm::begin([
'id' => 'dynamic-form',
'options' => [
'enctype' => 'multipart/form-data'
],
]); ?>
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
//'limit' => 4, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsProductImage[0],
'formId' => 'dynamic-form',
'formFields' => [
'id',
//'path',
'product_id',
],
]); ?>
<?php foreach ($modelsProductImage as $index => $modelProductImage): ?>
<div class="item panel panel-default col-md-3"><!-- widgetBody -->
<div class="panel-heading">
<span class="panel-title-address"><?= Yii::t('app','Image').':'. ($index + 1) ?></span>
<button type="button" class="pull-left remove-item btn btn-danger btn-xs"><i class="fa fa-minus"></i></button>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (!$modelProductImage->isNewRecord) {
echo Html::activeHiddenInput($modelProductImage, "[{$index}]id");
}
?>
<?php
$modelImage = $modelProductImage;
$initialPreview = [];
if ($modelImage) {
$pathImg = '/'.$modelImage->path;
$initialPreview[] = Html::img($pathImg, ['class' => 'file-preview-image']);
}
?>
<div class="">
<?= $form->field($modelProductImage, "[{$index}]file")->label(false)->widget(FileInput::classname(), [
'options' => [
'multiple' => false,
'accept' => 'image/*',
'class' => 'productImage-path',
'name' => $index
],
'pluginOptions' => [
'previewFileType' => 'image',
'showCaption' => false,
'showUpload' => false,
'browseClass' => 'btn btn-default btn-sm',
//'browseLabel' => Yii::t('app',' Pick Image'),
'browseIcon' => '<i class="glyphicon glyphicon-picture"></i>',
'removeClass' => 'btn btn-danger btn-sm',
//'removeLabel' => ' Delete',
'removeIcon' => '<i class="fa fa-trash"></i>',
'previewSettings' => [
'image' => ['width' => '138px', 'height' => 'auto']
],
'initialPreview' => $initialPreview,
'layoutTemplates' => ['footer' => '']
]
]) ?>
</div>
</div>
</div>
<?php endforeach; ?>
When i use getInstanceByName in controller it only return one file, and when i use getInstance it return NULL
and when i use getInstanceByname it save new file on old file(not as a new file)
Are you see example? docs
This is part of example from docs:
...
$modelsOptionValue = Model::createMultiple(OptionValue::classname());
Model::loadMultiple($modelsOptionValue, Yii::$app->request->post());
foreach ($modelsOptionValue as $index => $modelOptionValue) {
$modelOptionValue->sort_order = $index;
$modelOptionValue->img = \yii\web\UploadedFile::getInstance($modelOptionValue, "[{$index}]img");
}
...
Have you tried \yii\web\UploadedFile::getInstances()?
You can check the details here