Yii2 SendFile() displaying some characters instead of downloading - php

I have the controller code:
public function actionDownload($id) {
$download = Status::findOne($id);
$path = Yii::getAlias('#webroot').'/uploads/status/'.$download->image_web_filename;
if (file_exists($path)) {
return Yii::$app->response->SendFile($path,$download->image_src_filename);
exit;
} else {
throw new NotFoundHttpException("can't find {$download->image_src_filename} file");
}
}
I have the view code in the GridView:
['attribute'=>'Download',
'format'=>'raw',
'value' => function($data)
{
return
Html::a('Download file', ['status/download','id'=>$data->id],['class' => 'btn btn-primary']);
}
],
This is what displayed on the screen.The pdf is only downloaded when the I refresh the browser but this still remains on the screen what is the problem?:
%PDF-1.4 %�쏢 5 0 obj <> stream x��]K�%ECű%P4���y��.�u�#�Q �zt��P�0��_��'��gx����/3�n���zܞ���xaAR7o�s�<�;�����܈�o��w?8��]�y�/'�O�FU��#b㍤���G����͇'r����4�+B��{3���SW����'��<�������A�ǃ*x���N27r�$���V������w�_?��k�~���+�'wFr6��f! ��ȍ7�Ӡ���UG���g;=�2�j��Ǒ �oƱQƇfh�?�WҘ�0۟��/�l�E���i(�{��* ��'�W��8��T�j 2��p������\��aܵH�$�Ci��u��$j��QZ���aIk����\o���D2Y)�/FV��nġ�a����� �_ؐ��rf�� �7�*� �IN�J{�l����Cqr�D�������[�]9���E�7�����k�j���9N�\�EC��F����&ռ-����uJV����3����L!�f��x���F�����̈́��#��U����:*g��&C�ӤD��q�17�#Jg+�J����w��ߨ?M_�a���R�ݼ��zu%��\�#�7$M&���-dO"#�]�i�89�}��<��� m��04�I�bHJ �O�M��`f�Ϯ�E�{2}`���n�����.l���+cZ?�����6C��N��XZJW�ylȒ��"�D�ͧ�8s���q��o׉m��ݍx�6(��T�9Uɨ�g���x���\���'�Ͻ����BE��|��� p���9P]��R*����C��������jC�m���1��#K���׶Y���rt=�:�x����W����qr�便p4��"��B�}=�2������p��!x+�)zv���̳���\^*�R�ugȎ!J<��q�~���C��/��ˏU8�C7A0`�6x����6ۗ#�b���Ħ�(��Sk̍�"|����9�" �G�`#LD���e�B�Q���� d��[q�Z�aځ��-j�����Zk�}F4���l���y�T ��B��|���ҕ~/����a�+�7��Ai=W���1�

The problem that I had in this specific code is that I had to remove
<?php Pjax::begin(); ?> and <?php Pjax::end(); ?> and also 'pjax'=>true above and in the gridview column so that it worked I didnt alter anything in the actionDownload($id) code
Before editing(original erroneous code)
`....................................
<h3><?= Html::encode($this->title) ?></h3>
<p>
<?= Html::a('Create Status', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php Pjax::begin(); ?>
<?php
$gridColumns = [
['class' => 'kartik\grid\SerialColumn'],
'id',
'message',
'permissions',
'created_by',
'created_at',
// 'updated_at',
// 'image_src_filename',
//'image_web_filename',
['attribute'=>'Download',
'format'=>'raw',
'value' => function ($data) {
return
Html::a('Download file', ['status/download','id'=>$data->id], ['class' => 'btn btn-primary']);
}
],
];
?>
<?php
$export = ExportMenu::widget([
'dataProvider' => $dataProvider,
//'columns' => $gridColumns,
'fontAwesome' => true,
'exportConfig' => [
ExportMenu::FORMAT_HTML => false,
ExportMenu::FORMAT_TEXT => false,
ExportMenu::FORMAT_CSV => false,
ExportMenu::FORMAT_EXCEL => false,
ExportMenu::FORMAT_EXCEL_X => false,
],
]);
?>
<?php
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => $gridColumns,
'containerOptions' => ['style' => 'overflow: auto'], // only set when $responsive = false
'toolbar' => [
$export
],
'pjax' => true,
'bordered' => true,
'striped' => true,
'responsive' => true,
'floatHeader' => true,
'panel' => [
'type' => GridView::TYPE_PRIMARY,
'heading' => 'Forms Uploaded by Clients.',
],
]);
?>
<?php Pjax::end(); ?></div>`
After editing(original erroneous code)
`
<h3><?= Html::encode($this->title) ?></h3>
<p>
<?= Html::a('Create Status', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php
$gridColumns = [
['class' => 'kartik\grid\SerialColumn'],
'id',
'message',
'permissions',
'created_by',
'created_at',
// 'updated_at',
// 'image_src_filename',
//'image_web_filename',
['attribute'=>'Download',
'format'=>'raw',
'value' => function ($data) {
return
Html::a('Download file', ['status/download','id'=>$data->id], ['class' => 'btn btn-primary']);
}
],
];
?>
<?php
$export = ExportMenu::widget([
'dataProvider' => $dataProvider,
//'columns' => $gridColumns,
'fontAwesome' => true,
'exportConfig' => [
ExportMenu::FORMAT_HTML => false,
ExportMenu::FORMAT_TEXT => false,
ExportMenu::FORMAT_CSV => false,
ExportMenu::FORMAT_EXCEL => false,
ExportMenu::FORMAT_EXCEL_X => false,
],
]);
?>
<?php
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => $gridColumns,
'containerOptions' => ['style' => 'overflow: auto'], // only set when $responsive = false
'toolbar' => [
$export
],
'bordered' => true,
'striped' => true,
'responsive' => true,
'floatHeader' => true,
'panel' => [
'type' => GridView::TYPE_PRIMARY,
'heading' => 'Forms Uploaded by Clients.',
],
]);
?>`
Thats all !! I found out.

Just add
ob_clean();
before
return Yii::$app->response->SendFile($path,$download->image_src_filename);
.
ob_clean() will clean your output and fix the problem .
It worked for me.
Thanks

It is look like you need header for that.
try with this code:
public function actionDownload($id) {
header("Content-type:application/pdf");
........
if is not working try to add this header too
header("Content-Disposition:attachment;filename='filename.pdf'");

Related

Getting unknown property in Yii

under the course content there, I want to make the Active column to show either "Yes" or **"No"**At first it was showing "1" or "0", but that's not what I want to show. These are my attempted codes, and I'm getting this error. Appreciate it if anyone can please guide me.
Unknown Property – yii\base\UnknownPropertyException
Getting unknown property: app\models\Coursecontent::isActive
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\DetailView;
/* #var $this yii\web\View */
/* #var $model app\models\Course */
$this->title = $model->course_name;
$this->params['breadcrumbs'][] = ['label' => 'Courses', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
\yii\web\YiiAsset::register($this);
?>
<div class="course-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('<< Back', ['index'], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Update', ['update', 'id' => $model->course_id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->course_id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'course_name',
'description',
['attribute' => 'active', 'value' => $model->isActive,'contentOptions' => ['style' => $model->active == 1 ? 'color:green' :'color:red']],
'lastupdate',
],
]) ?>
<h2>Course Content</h2>
<?= Html::a('Create Coursecontent', ['coursecontent/create'], ['class' => 'btn btn-success']) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'chapter_name',
'description',
'video_link',
['attribute' => 'active',
'value' => function ($model, $key, $index, $column) {return $model->isActive;},
'contentOptions' => function ($model, $key, $index, $column) {
return $model->active == 1 ? ['style' => 'color:green'] : ['style' => 'color:red'];
}],
['class' => 'yii\grid\ActionColumn',
'contentOptions' => ['class' => 'text-center'],
'buttons' => [
'view' => function ($url,$model) {
return Html::a('<span class="glyphicon glyphicon-eye-open"></span>',['coursecontent/view', 'id' => $model->coursecontent_id]);
},
'update' => function ($url,$model) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>',['coursecontent/update', 'id' => $model->coursecontent_id]);
},
'delete' => function ($url,$model) {
return Html::a('<span class="glyphicon glyphicon-trash"></span>',['coursecontent/delete', 'id' => $model->coursecontent_id],
['data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]);
},
]],
],
]); ?>
</div>
Have to make 2 changes to your code.
Change all $model->isActive to $model->active.
Return "Yes" or "No" depending to $model->active value.
Update DetailView:
[
'attribute' => 'active',
'value' => function ($model) {
return $model->active ? "Yes" : "No";
},
'contentOptions' => ['style' => $model->active ? 'color:green' :'color:red']
],
Update GridView:
[
'attribute' => 'active',
'value' => function ($model) {
return $model->active ? "Yes" : "No";
},
'contentOptions' => function ($model, $key, $index, $column) {
return $model->active ? ['style' => 'color:green'] : ['style' => 'color:red'];
}
],

Yii2 Pjax Gridview in Modal will reload page instead of updating

I had a problem with Pjax, actually on somepage I load a view in Modal, and in this modal I use GridView with filter option with selectbox. When user changes the filter, the content will not be updated, but the page will be redirected to the filtered URL (Gridview with data updated).
When the view is working outside the modal it works fine, and update its contents!
Here is my code:
index.php, here I load my modal:
<div>
<?php
Modal::begin([
'header' => '',
'id' => 'modal-window',
'class' => 'modal',
'footer' => 'Close',
'clientOptions' => ['backdrop' => false]
]);
Modal::end();
?>
And in view:
<?php Pjax::begin(['id' => 'pjax_translation','enablePushState' => false, 'timeout' => false,]); ?>
<div class="row">
<h1><?= Html::encode($this->title) ?></h1>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'filterUrl' => Url::to(["translate/view" , "id" => $id ]),
'tableOptions' => ['class' => 'table table-striped table-bordered translate-list',"style"=> ""],
'options' => ['data-pjax' => true ],
'columns' => [
[
'attribute' => 'language',
'filter' => $arrLanguage,
'content'=> function($model) use ($arrLanguage){
return isset($arrLanguage[$model->language])? $arrLanguage[$model->language] : "" ;
},
'headerOptions' => ['width' => '150'],
],
[
'attribute' => 'translation',
],
],
]); ?>
</div>
<?php Pjax::end(); ?>
And in my controller the code is:
public function actionView($id)
{
$view = "view";
$searchModel = new TranslateMessageSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->query->andFilterWhere([
'id' => $id,
]);
if (Yii::$app->request->isAjax) {
\Yii::$app->response->format = 'json';
$html = $this->renderAjax($view, [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'id'=>$id,
]);
return ['success' => true, 'html' => $html] ;
} else {
return $this->render($view, [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'id'=>$id,
]);
}
}
i found finally a solution after three days testing everything. I will post it here, maybe it could be usefull for someone who has the same problem.
I just put in my view.php the following js at the top:
$js = "$(document).on('submit', 'form[data-pjax]', function(event) {
$.pjax.submit(event, '#pjax_translation', {
'push': false,
'replace': false,
'timeout': 5000,
'scrollTo': false,
'maxCacheLength': 0
});
});";
$this->registerJs($js);
and everything is work fine now :)
this is working for me:
<?php Modal::begin([
'header' => '',
'id' => 'modal-window',
'class' => 'modal',
'toggleButton' => ['label' => 'click me'],
'footer' => 'Close',
'clientOptions' => ['backdrop' => false]
]); ?>
<?php Pjax::begin() ?>
<?php $form = ActiveForm::begin(['options' => ['data-pjax' => 1]]) ?>
<?= date('Y-m-d H:i:s', time()) ?> <button type="submit">click this</button>
<?php ActiveForm::end() ?>
<?php Pjax::end() ?>
<?php Modal::end(); ?>
PS: Maybe your page gets reloaded because you hit Pjax timeout

Add filter on checkbox column Yii2 Gridview widget

Can you help me to add a filter on checkbox column on Grid view widget yii2? I used yii\grid\CheckboxColumn to add the check box column in the Gridview on my index.php. But I couldn't add a filter above the column as the other columns. Please look into my code below.
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
['label' => 'Client', 'attribute' => 'name', 'value' => 'client.view', 'format' => 'raw'],
'postCode',
'start',
'end',
[
'attribute' => 'categoryID',
'value' => 'category.name',
'filter' => ArrayHelper::map(Servicecategory::find()->where(['status' => true])->asArray()->all(), 'id', 'name')
],
[
'attribute' => 'status',
'headerOptions' => ['style' => 'width:12%'],
'value' => 'Status',
'filter' => array_filter(\app\models\Booking::$statuses),
'filterInputOptions' => ['class' => 'form-control', 'prompt' => 'All']
],
['class' => 'yii\grid\CheckboxColumn',
'header' => 'follow Up',
'contentOptions' => ['class' => 'text-center'],
'checkboxOptions' => function($model, $key, $index) {
$url = \yii\helpers\Url::to(['booking/followup/' . $model->id]);
return ['onclick' => 'js:followUp("' . $url . '")', 'checked' => $model->followUpEmailSent ? true : false, 'value' => $model->followUpEmailSent];
}
],
['class' => 'yii\grid\ActionColumn',
'headerOptions' => ['style' => 'width:10%'],
'template' => '{view} {approval} {update} {delete} ',
'buttons' => [
/* 'view' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', ['/booking/review/' . $model->id], [
'title' => Yii::t('app', 'Review'),
]);
}, */
'approval' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-ok"></span>', ['/booking/approval/' . $model->id], [
'title' => Yii::t('app', 'Additional Details'),
'class' => 'error',
]);
}
],
],
],
]);
Following is the checkbox column.
['class' => 'yii\grid\CheckboxColumn',
'header' => 'follow Up',
'contentOptions' => ['class' => 'text-center'],
'checkboxOptions' => function($model, $key, $index) {
$url = \yii\helpers\Url::to(['booking/followup/' . $model->id]);
return ['onclick' => 'js:followUp("' . $url . '")', 'checked' => $model->followUpEmailSent ? true : false, 'value' => $model->followUpEmailSent];
}
],
Can someone help with this?
You may use your Gii tool-> CRUD generator to create your filter file.
Then you can pass your params to search model like this:
$searchModel = new SearchModel;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
You will need to return your $dataProvider from SearchModel
Use the search file for implement filters on grid.
I suggest that do not use gridview filter in your case.
Write your search related code in search file and add checkbox on search form.
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<div class="ideas-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?php echo $form->field($model, 'name[]')->checkboxList(
['a' => 'Item A', 'b' => 'Item B', 'c' => 'Item C']);
?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>

add a button to grid view in yii2

i'm a new yii2 developer !
i made a GridView and the code is shown below :
<?php Pjax::begin(); ?> <?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\ActionColumn'],
['class' => 'yii\grid\CheckboxColumn'],
['class' => 'yii\grid\SerialColumn'],
'id',
'countryCode',
'countryName',
'currencyCode',
],
]); ?>
<?php Pjax::end(); ?>
a screenshot of output :
OUTPUT
now i want to have a column contain some button and that button for example open a page or somthing else !
my problem is how can i create that column ?
You can also add the button (or as many as you like) to the existing action column like this
<?= GridView::widget([
::
::
'columns' => [
[
'class' => 'yii\grid\ActionColumn',
'template' => '{view} {update} {delete} {myButton}', // the default buttons + your custom button
'buttons' => [
'myButton' => function($url, $model, $key) { // render your custom button
return Html::a(..);
}
]
]
::
::
'currencyCode'
]
]); ?>
Example:
<?php Pjax::begin(); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\ActionColumn'],
['class' => 'yii\grid\CheckboxColumn'],
['class' => 'yii\grid\SerialColumn'],
'id',
'countryCode',
'countryName',
'currencyCode',
[
'label' => 'My Label',
'format' => 'raw',
'value' => Html::a('Click me', ['site/index'], ['class' => 'btn btn-success btn-xs', 'data-pjax' => 0])
]
],
]); ?>
<?php Pjax::end(); ?>
Try this way:
[
'header' => 'Button',
'content' => function($model) {
return Html::a(..);
}
],
More Info

how to disable update in gridview for pjax in yii2?

I am new in yii2, Right now i am creating sample crud appliacation. I used pjax for gridview, It is working fine for me, My problem is when i update my row at that time pjax also calling now i want to disable this pjax for update button. How can i resolve this issue ? Here is my code
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\helpers\Url;
use yii\widgets\Pjax;
/* #var $this yii\web\View */
/* #var $searchModel backend\models\PostSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Posts';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="post-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Post', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php \yii\widgets\Pjax::begin(
['id' => 'StickerList', 'timeout' => false, 'enablePushState' => false, 'clientOptions' => ['method' => 'GET']]
); ?>
<?= GridView::widget([
'dataProvider' => $model->search(),
'filterModel' => $model,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute'=>'PostType',
'filter'=>Html::activeDropDownList($model, 'PostType',array(""=>"All","1"=>"Status","2"=>"Images","3"=>"Video"),['class'=>'form-control','prompt' => 'Select Post Type']),
],
'PostTitle',
[
'header' => 'Artist',
'attribute' => 'ArtistName',
],
[
'header' => 'Date Posted',
'attribute' => 'DatePosted',
'filter' => false,
],
[
'header' => '# Likes',
'attribute' => 'TotalLikes',
'filter' => false,
],
[
'header' => '# Comments',
'attribute' => 'TotalComments',
'filter' => false,
],
[
'header' => 'Exclusive',
'attribute' => 'IsExclusive',
'filter'=>Html::activeDropDownList($model, 'IsExclusive',array(""=>"All","0"=>"Normal","1"=>"Exclusive"),['class'=>'form-control','prompt' => 'Select Exclusive']),
],
[
'header' => 'Status',
'attribute' => 'Status',
'filter'=>Html::activeDropDownList($model, 'Status',array(""=>"All","1"=>"Active","2"=>"Inactive"),['class'=>'form-control','prompt' => 'Select Status']),
],
[
'class' => 'yii\grid\ActionColumn',
'template'=>'{update}',
'buttons' => [
'update' => function ($url,$model) {
$url = Url::toRoute('post/update?id='.$model['PostID']);
return Html::a('<span class="glyphicon glyphicon-pencil"></span>',$url);
},
],
],
],
]); ?>
<?php \yii\widgets\Pjax::end(); ?>
</div>
You should need to add [ 'data-pjax' => false ] or [ 'data-pjax' => '0' ] in anchor tag options of update button.
For example,
[
'class' => 'yii\grid\ActionColumn',
'template'=>'{update}',
'buttons' => [
'update' => function ($url,$model) {
$url = Url::toRoute('post/update?id='.$model['PostID']);
return Html::a('<span class="glyphicon glyphicon-pencil"></span>',$url, ['data-pjax' => '0']);
},
],
]

Categories