Im using kartik-mpdf library to generate pdf’s of my gridviews, the thing is I want to pass $dataProvider and $searchModel from index.php to the view that is going to be renderer as pdf document (pdf.php), So, when I search on index and click the button ‘Generar pdf’ it calls action GenerarPdf on AlumnoController and loads the same $searchModel and $dataProvider of index action into pdf.php gridview and generate the pdf file.
Here’s the code.
AlumnoController.php - actionGenerarPdf
public function actionGenerarPdf($searchModel, $dataProvider)
{
Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
$formatter = \Yii::$app->formatter;
$pdf = new Pdf([
'mode' => Pdf::MODE_CORE, // leaner size using standard fonts
'destination' => Pdf::DEST_BROWSER,
//Se renderiza la vista "pdf" (que abrirá la nueva ventana)
'content' => $this->renderPartial('pdf', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider
]),
'options' => [
// any mpdf options you wish to set
],
'methods' => [
'SetTitle' => 'SIE: Sistema de Informacion Estudiantil',
'SetSubject' => 'Generating PDF files via yii2-mpdf extension has never been easy',
'SetHeader' => ['SIE: Sistema de Información Estudiantil||Generado el: ' . $formatter->asDate(date("r"))],
'SetFooter' => ['|Página {PAGENO}|'],
'SetAuthor' => 'SIE: Sistema de información Estudiantil',
'SetCreator' => 'Juan Carlos Reyes Suazo',
// 'SetKeywords' => 'Sie, Yii2, Export, PDF, MPDF, Output, yii2-mpdf',
]
]);
return $pdf->render();
}
index.php
<p>
<?php
if (User::isSuperAdmin(Yii::$app->user->identity->id)){
echo Html::a('Crear Alumno', ['create'], ['class' => 'btn btn-success']);
echo Html::a('Ver PDF', [
'/alumno/generar-pdf',
'searchModel' => $searchModel,
'dataProvider' => $dataProvider
],
[
'class' => 'btn btn-success',
'target'=>'_blank',
'data-toggle'=>'tooltip',
// 'title'=>'Will open the generated PDF file in a new window'
]);
}
?>
</p>
pdf.php
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
['attribute' => 'nombre',
'format' => 'raw',
'value'=>function ($data) {
return Html::a($data['nombre'],['alumno/view', 'id' => $data['id']]);
},
],
//'rut',
['attribute' => 'curso_id',
'format' => 'raw',
'value'=>function ($data) {
return Html::a($data['curso_id'],['curso/view', 'id' => $data['curso_id']]);
},
],
//'fecha_nacimiento',
//'fono',
//'direccion',
//'email:email',
//'apoderado',
['attribute' => 'apoderado',
'format' => 'raw',
'value'=>function ($data) {
if ($data->apoderado_id != null)
return Html::a($data->apoderado->nombre, ['apoderado/view', 'id' => $data['apoderado_id']]);
else
return null;
},
],
//'apoderado_suplente',
//'fono_apoderado',
//'fono_apoderado_sup',
//'antecedentes_medicos',
//'grupo_sanguineo',
//'programa_integracion',
//'taller_artistico',
//'anotaciones',
['class' => ActionColumn::className(), 'template' => '{update} {delete}'],
],
]); ?>
Im getting Bad Request (#400)
Se recibieron datos erróneos para el parámetro “searchModel”
Any help would be appreciated.
I solved this by using sessions, and I generated $searchModel and $dataProvider in actionGenerarPdf instead of sending them by a button.
I'll quote #softark from yii forum
"You can’t pass $searchModel and $dataProvider as the query parameters to an action method, because they are not such simple variables that could be converted to simple strings.
So you have to create the search model and the data provider in your actionGenerarPdf method.
In order to get back the search parameters used in the index action, you can store the query parameters in the session and retrieve them in actionGenerarPdf."
https://forum.yiiframework.com/t/print-gridview-search-in-pdf-using-kartik-mpdf-extension-solved/124925
Here's the code
public function actionIndex()
{
$searchModel = new AlumnoSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$session = Yii::$app->session;
$session->open();
$session['query_params'] = json_encode(Yii::$app->request->queryParams);
$session->close();
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
public function actionGenerarPdf()
{
$session = Yii::$app->session;
$session->open();
$queryParams = isset($session['query_params']) ? json_decode($session['query_params'], true) : [];
$session->close();
$searchModel = new AlumnoSearch();
$dataProvider = $searchModel->search($queryParams);
Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
$formatter = \Yii::$app->formatter;
$pdf = new Pdf([
'mode' => Pdf::MODE_CORE, // leaner size using standard fonts
'defaultFontSize' => 18,
'orientation' => Pdf::ORIENT_PORTRAIT,
'destination' => Pdf::DEST_BROWSER,
//Se renderiza la vista "pdf" (que abrirá la nueva ventana)
'content' => $this->renderPartial('pdf', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider]),
'options' => [
// any mpdf options you wish to set
],
'methods' => [
'SetTitle' => 'SIE: Sistema de Informacion Estudiantil',
'SetSubject' => 'Generating PDF files via yii2-mpdf extension has never been easy',
'SetHeader' => ['SIE: Sistema de Información Estudiantil||Generado el: ' . $formatter->asDate(date("r"))],
'SetFooter' => ['|Página {PAGENO}|'],
'SetAuthor' => 'SIE: Sistema de información Estudiantil',
'SetCreator' => 'Juan Carlos Reyes Suazo',
// 'SetKeywords' => 'Sie, Yii2, Export, PDF, MPDF, Output, yii2-mpdf',
]
]);
return $pdf->render();
}
I hope this helps others who want to achieve the same
Related
My controller:
$params = Yii::$app->request->queryParams;
$query4 = (new \yii\db\Query())
->select(['monthsubmit', 'modeler'])
->from('sku3d')
->groupBy(['monthsubmit', 'modeler'])
->orderBy(['monthsubmit'=>SORT_DESC]);
$query4->andFilterWhere(['like', 'monthsubmit', $params['monthsubmit']])
->andFilterWhere(['like', 'modeler', $params['modeler']]);
$dataProvider4 = new ActiveDataProvider([
'query' => $query4,
]);
MY view:
<?php echo GridView::widget([
'dataProvider' => $dataProvider4,
'filterModel' => true,
'pjax'=>true,
'panel' => [
'type' => GridView::TYPE_PRIMARY,
'heading' => '<h3 class="panel-title"><i class="glyphicon glyphicon-user"></i>Submitted SKU by Month</h3>',
],
'columns' => [
// 'monthsubmit',
[
'attribute'=>'monthsubmit',
'filter' => Html::input('string', 'monthsubmit')
'width'=>'310px',
'group'=>true, // enable grouping
],
[
'attribute'=>'modeler',
'width'=>'180px',
'filter' => Html::input('string', 'modeler')
'group'=>true, // enable grouping
],
]
]);
?>
I have created sqlDataProvider in my controller and its working. My problem is when i try to create a filter option since im not using the search model for my gridview, it return error Undefined index: monthsubmit.
Please tell me where I'm wrong.
Thank you.
In your controller, you should do as this
$modeler = Yii::$app->request->get('modeler');
$monthsubmit = Yii::$app->request->get('monthsubmit');
$query4 = (new \yii\db\Query())
->select(['monthsubmit', 'modeler'])
->from('sku3d')
->groupBy(['monthsubmit', 'modeler'])
->orderBy(['monthsubmit'=>SORT_DESC]);
$query4->andFilterWhere(['like', 'monthsubmit', $monthsubmit])
->andFilterWhere(['like', 'modeler', $modeler]);
$dataProvider4 = new ActiveDataProvider([
'query' => $query4,
]);
yii2-scroll-pager extension used but that extension not work.
Extesion Link
View File -1: index.php
echo ListView::widget( [
'dataProvider' => $dataProvider,
'itemView' => '_item',
'pager' => ['class' => \kop\y2sp\ScrollPager::className()]] );
View File-2 : _item
<?php $model->name;?><?php $model->age;?><?php $model->mobile;?>
Controller File : SiteController.php
$dataProvider = new ActiveDataProvider([
'query' => backend\models\Product::find(),
]);
return $this->render('index', [
'dataProvider' => $dataProvider,
]);
where is wrong in that code please hep guys
add this to your pager config
'triggerOffset'=>5
'pager' => [
'class' => \kop\y2sp\ScrollPager::className(),
'triggerOffset'=>5
]
How to access variable ($imodel->grade) in tampil.php page and then subsequently put on the page view.php with post method. Sorry for the question, i'm newbie in OOP, MVC and Yii. Please help me guys
Here is The code of actionIndex:
public function actionIndex()
{
$imodel = new Grade();
if($imodel->load(Yii::$app->request->post()))
{
$imodel->load(Yii::$app->request->post());
$imodel->grade;
$query = Nilaiharian::find(); //select nis, $grade, nama from nilaiharian
$dataProvider = new ActiveDataProvider(['query' => $query,]);
return $this->render('tampil', ['imodel' => $imodel, 'dataProvider' => $dataProvider,] );
}
else
{
return $this->render('index', ['imodel' => $imodel, ] );
}
}
And this is a code of tampil.php
<?php
echo "Nilai untuk ".$imodel->grade;
echo "<br>";
echo GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'nis',
$imodel->grade,
'nama',
['class' => 'yii\grid\ActionColumn',
'template' => '{view}{update}{delete}',
'buttons' => [
'view' => function ($url, $model) {
return Html::a('<i class="glyphicon glyphicon-eye-open"></i>',
$url, ['title' => Yii::t('app', 'Show'), 'name'=>'view', 'value'=>'view', 'style' => 'margin-right:10px;', ]);
},
'update' => function ($url, $model) {
return Html::a('<i class="glyphicon glyphicon-pencil"></i>',
$url, ['title' => Yii::t('app', 'Edit'), 'name'=>'update', 'style' => 'margin-right:10px;', ]);
},
'delete' => function ($url, $model) {
return Html::a('<i class="glyphicon glyphicon-trash"></i>',
$url, ['title' => Yii::t('app', 'Delete'), 'name'=>'delete', 'data-confirm'=>'Are you sure you want to delete this record?']);
}
]
],
],
]);
?>
It there any way to make 'data-confirm' => Please enter the number' not just confirm but some like JS prompt and get imputed values to sent it to controller?
<?php \yii\widgets\Pjax::begin(['id' => 'pjax-orders_table','clientOptions' => ['method' => 'POST'], 'enablePushState'=>false]) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'id'=>'orders_table',
'columns' => [
['class' => 'yii\grid\SerialColumn'],
///some columns
[
'class' => 'yii\grid\ActionColumn',
'template' => '{update} {delete}{some}',
'buttons' => [
'some' => function ($url,$model,$key) {
if($model->status=='not confirm')
{
return Html::a('<span class="glyphicon glyphicon-trash"</span>',['my/some', 'id' => $model->id],[
'title' => Yii::t('yii', 'Delete'),
'data-confirm' => Please enter the number',
'data-method' => 'post',
]);
}
},
],
],
],
]); ?>
<?php \yii\widgets\Pjax::end() ?>
In controller
public actionSome()
{ $dataProvider = new ActiveDataProvider();
$dataProvider->query = Orders::find()->all();
return $this->render('some',['dataProvider'=>$dataProvider]);
}
instead of Html::a() use Html::button()where button id = some_item_id and then write this JS code
$('.buttons_class').click(function(){
var selection;
do{
selection = parseInt(window.prompt("Please enter a number from 1 to 100", ""), 10);
}
while(isNaN(selection));
if(!isNaN(selection))
{
$.post("some",{id:45,prompt_value:selection}, function(response)
{
console.log(response);
$.pjax.reload({container:'#pjax-orders_table'});
});
}
})
I'm trying to use fill my listView using an ArrayDataProvider. However the dataProvider consists of Arrays, not objects. I ran into this problem because the category in the model is an id, where I need the name corresponding to that id from another table. Hence I created an Array where the id is the corresponding name.
private function getDataProvider()
{
return new ArrayDataProvider([
'allModels'=>$this->getFaqs(), // returns array of faqs
'sort'=>[
'attributes'=>['id','category','question','answer']],
'pagination'=>[
'pageSize'=>10,
],
]);
}
Here is my ListView widget
echo ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => function($dataProvider, $key, $index, $widget)
{
return Html::a($dataProvider->question,
Url::toRoute(['faq/view', 'id' => $dataProvider->primaryKey]));
}
]);
It works, I use it like this
$dataProvider = new ArrayDataProvider([
'allModels' => [['name' => '0am - 6am'], ['name' => '6am - 9pm'], ['name' => '9am - 12pm'], ['name' => '12pm - 3pm'], ['name' => '3pm - 6pm']],
]);
<?= ListView::widget([
'dataProvider' => $dataProvider,
'layout' => "{items}",
'itemOptions' => ['class' => 'item', 'style' => 'margin-bottom: 5px;'],
'itemView' => function ($model, $key, $index, $widget) use ($transportRun) {
//return print_r($model, true);
return Html::a(Html::encode($model['name']), ['delivery/index', 'DeliverySearch' => ['transport_run' => $transportRun, 'timeslot' => $key]], ['class' => 'btn btn-lg btn-primary btn-block']);
},
]) ?>
ListView and GridView can use any class that implements yii\data\DataProviderInterface. You can take a look here http://www.yiiframework.com/doc-2.0/yii-data-dataproviderinterface.html to see who implements it, so you can use any of those classes on both ListView and GridView.
You should also be able to do a
'allModels'=>$this->faqs, // returns array of faqs