Yii2 dynamic form (File upload) - yii2

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

Related

Yii2 Pjax reloads the page even with renderPartial

I am sending Pjax request which reloads the whole page even when I am using renderPartial. The pjax container is #promo-products than why it reloads the whole page not only fill the container with the desired results ? If I var_dump($child_products);die; it shows the result right in the container but without die it reloads the page. Also tried to render a partial view ( like _children lets say ) but the result was the same. What is my mistake?
Controller:
public function actionCreate()
{
$model = new Promotion();
$products = [];
$success = null;
$child_products = [];
if(Yii::$app->request->isPjax){
$parent_id = Yii::$app->request->get('parent_id');
if($parent_id){
$parent_children = ProductChild::find()->where(['id_in' => $parent_id])->all();
foreach ($parent_children as $child){
$child_products[$child['id']][] = $child;
}
}
}
if (!Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
$transaction = Yii::$app->db->beginTransaction();
try{
if($model->save()){
//save products
$model->saveProducts();
$transaction->commit();
return $this->redirect(['index', 'success' => 1]);
} else {
throw new \Exception("Some error occurred.");
}
}catch (\Exception $e){
$success = 3;
$model = new Promotion();
$transaction->rollBack();
}
}
if(Yii::$app->request->isPjax){
return $this->renderPartial('create', [
'child_products' => $child_products,
]);
}
return $this->render('create', [
'model' => $model,
'products' => $products,
'success' => $success,
'child_products' => $child_products,
]);
}
And my view:
<?php
use yii\widgets\ActiveForm;
use backend\helpers\Header;
use kartik\select2\Select2;
use yii\web\JsExpression;
use backend\helpers\CGrowl;
\backend\assets\JquerySteps::register($this);
\backend\assets\DateTimePickerAsset::register($this);
/* #var $this yii\web\View */
/* #var $model backend\models\Contact */
/* #var $form yii\widgets\ActiveForm */
$this->registerJs("
$('#promotion-start_date').bootstrapMaterialDatePicker({ format: 'YYYY-MM-DD HH:mm:ss' });
$('#promotion-end_date').bootstrapMaterialDatePicker({ format: 'YYYY-MM-DD HH:mm:ss' });
",
\yii\web\View::POS_LOAD,
'datetime-picker-init'
);
if (isset($success)) {
echo CGrowl::setFormResult((int)$success, $this);
}
?>
<div class="row page-titles" style="background-image: url('<?= Yii::getAlias('#backend-image') ?>/theme/images/heading-title-bg.jpg')">
<div class="col-md-12">
<h4 class="text-white"><?= Yii::t('app', 'Promotion') ?></h4>
</div>
<div class="col-md-6">
<?= Header::renderBreadcrumbs($this) ?>
</div>
</div>
<div class="row" id="validation">
<div class="col-12">
<div class="card wizard-content">
<div class="card-body">
<div class="panel-body">
<?php $form = ActiveForm::begin([
'options' => [
'class' => 'validation-wizard wizard-circle'
],
]); ?>
<h6><?= Yii::t('app', 'Main info') ?></h6>
<section>
<div class="row">
<div class="col-sm-6">
<?= $form->field($model, 'type')->widget(Select2::class, [
'data' => [
1 => Yii::t('app', 'Percentage'),
2 => Yii::t('app', 'Price'),
],
'options' => [
'placeholder' => Yii::t('app', 'Type')
],
'pluginOptions' => [
'allowClear' => true
]
]) ?>
</div>
<div class="col-sm-6">
<?= $form->field($model, 'value')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-6">
<?= $form->field($model, 'start_date')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-6">
<?= $form->field($model, 'end_date')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($model, 'products')->widget(Select2::class, [
'initValueText' => $products,
'options' => [
'multiple' => true
],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'language' => [
'errorLoading' => new JsExpression("function(){return 'Waiting for results ...'; }"),
],
'ajax' => [
'url' => \yii\helpers\Url::to(['async/products']),
'dataType' => 'json',
'data' => new JsExpression("function(params){return {q:params.term}; }")
],
'escapeMarkup' => new JsExpression("function(markup){return markup;}"),
'templateResult' => new JsExpression("function(city){return city.text;}"),
'templateSelection' => new JsExpression("function(city){return city.text;}")
],
'pluginEvents' => [
'select2:select' => "function(){
let url = location.href.split('?')[0]
$.pjax.defaults.timeout = false
$.pjax({
url: url,
data: {
parent_id: this.value
},
container: '#promo-products'
})
}"
]
]) ?>
</div>
<div class="col-sm-8">
<label for=""><?= Yii::t('app', 'Varieties')?></label>
<div class="table-responsive">
<table>
<?php \yii\widgets\Pjax::begin(['id' => 'promo-products']) ?>
<tbody>
<?php
foreach ($child_products as $child){
echo $child->id;
}
?>
</tbody>
<?php \yii\widgets\Pjax::end() ?>
</table>
</div>
</div>
<div class="col-sm-12">
</div>
</div>
</section>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
</div>
</div>

Yii2 uploadfile image from model method beforeSave

i try to upload 4 or less images, the ajax validation do not return any error, but on submit i get the follow:
"errors": {
"imageFiles": [
"Please upload a file."
]
}
attr:
/**
* #var UploadedFile[]
*/
public $imageFiles;
Rules:
return [
[['imageFiles'], 'required', 'on' => self::REPORT_STEP1],
[['imageFiles'], 'file', 'skipOnEmpty' => false, 'maxFiles' => 4],
];
BeforeSave:
public function beforeSave($insert)
{
$files_urls = [];
$this->imageFiles = UploadedFile::getInstances($this, 'imageFiles');
foreach ($this->imageFiles as $file) {
$path = Url::to(['/uploads/reports/'], true) . Yii::$app->security->generateRandomString() . '.' . $file->extension;
$file->saveAs($path);
$files_urls[] = $file->name;
}
$this->img_url = json_encode($files_urls);
return parent::beforeSave($insert); // TODO: Change the autogenerated stub
}
Form:
<?php $form = ActiveForm::begin([
'enableAjaxValidation' => true,
'options' => [
'enctype' => 'multipart/form-data'
]
]) ?>
<?= $form->field($model, 'imageFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>
<div class="form-group">
<?= Html::submitButton('Siguiente', ['class' => 'btn btn-standard']) ?>
</div>
<?php ActiveForm::end() ?>

Insert multiple records of a same table Yii2

I want to insert same record in one table. I have only one input array in the below form but i want to save multiple time record for label input array.
my form is
<div class="surveys-questions-form">
<?php $form = ActiveForm::begin(); ?>
<?php
if(isset($_GET['option_id']) and $_GET['option_id'] > 0)
$id= $_GET['option_id'];
else
$id= $model->option_id;
echo $form->field($model, 'question_id')->hiddenInput(['value' => $id])->label(false);
?>
<div class="col-md-6">
<div id="question_wrapper">
<?= $form->field($model, 'type')->dropDownList([ 'text' => 'Text', 'numbers' => 'Numbers', 'date' => 'Date', 'texarea' => 'Texarea', 'checkbox' => 'Checkbox', 'radio' => 'Radio', 'rating' => 'Rating', ], ['prompt' => '']) ?>
<div id="add_more_field">
<?= $form->field($model, 'label[]')->textInput(['maxlength' => true]) ?>
</div>
<div class="form-group">
<?php
echo Html::a('Add more', 'javascript:void(0);', [
'id' => 'surveys-questions-new-button',
'class' => 'pull-right btn btn-primary btn-xs'
])
?>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
and controller
public function actionCreate()
{
$model = new QuestionsOptions();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->option_id]);
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
Give me the following error when i try to submit form.
Label must be a string.
My $_POST array
Array
(
[_csrf-backend] => LXBhajI3YVpOIikeRWYHYkNCAD4Kb1ZrQzwER21GL2MdCTgkWm5ZDQ==
[QuestionsOptions] => Array
(
[question_id] => 47
[type] => numbers
[label] => Array
(
[0] => Label1
[1] => Label2
[2] => Labe3
)
)
)
If you want to save multiple record use loop i suggest you to use foreach loop it is best
public function actionCreate()
{
$model = new QuestionsOptions();
if ($model->load(Yii::$app->request->post())) {
if(sizeof(array_filter($_POST['QuestionsOptions']['label'])) > 0){
foreach($_POST['QuestionsOptions']['label'] as $key => $row){
$model->setIsNewRecord(true);
$model->id = null;
$model->label = $row;
$model->save();
}
}
return $this->redirect(['view', 'id' => $model->option_id]);
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}

Pass data from a form to a controller in 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.

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,)