How to display Image in gridview yii2 - yii

I'm new to yii, i want to display an image in gridview table, anyhelp will be appreciated, below is my code.
view....
<?= GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => [
//['class' => 'yii\grid\SerialColumn'],
'product_id',
'name',
'descr',
'price',
//'image',
[
'attribute'=>'image',
'label'=>'Image',
'format'=>'html',
'value' => function ($data) {
$url = \Yii::getAlias('#backend/web/').$data['image'];
return Html::img($url, ['alt'=>'myImage','width'=>'70','height'=>'50']);
}
],
'views',
['class' => 'yii\grid\ActionColumn'],
],
'tableOptions' =>['class' => 'table table-striped table-bordered'],
I'm using dataProvider and below is my controller
public function actionIndex()
{
$searchModel = new ProductSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
//$models = $dataProvider->getModels();
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
//'models' => $models,
]);
}
The above code is not working fine no image display only the img alt shown
Any help on how to get this work, thanks

Here is the solution :
[
'attribute' => 'Icon',
'format' => 'html',
'label' => 'Icon',
'value' => function ($data) {
return Html::img(Yii::$app->request->BaseUrl.'/uploads/path/' . $data['Icon'],
['width' => '60px']);
},
],

Check you image path,
You can use
Yii::$app->request->baseUrl
If your index file is on root directory
$url =Yii::$app->request->baseUrl.'/'.$data['image'];

Specify 'format' to 'raw' for image column and $data should be and object, so 'image' field is accessible with $data->image.
[
'attribute'=>'image',
'label'=>'Image',
'format'=>'raw',
'value' => function ($data) {
$url = \Yii::getAlias('#backend/web/').$data->image;
return Html::img($url, ['alt'=>'myImage','width'=>'70','height'=>'50']);
}
],

Related

Kartik Grid Editable Column with expandrow styling not applying

When I pull in a kartik expandable row grid, using pjax the editablecolumn styling is not being applied. What can I do to apply css to this column?
<?php echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'pjax' => false,
'columns' => [
[
'class' => 'kartik\grid\ExpandRowColumn',
'value' => function ($model, $key, $index, $column){
return GridView::ROW_COLLAPSED;
},
'detailUrl' => 'index.php?r=controller/detail'
],
Expanded View
<?php echo GridView::widget([
'dataProvider' => $dataProvider,
'pjax'=> true,
'columns' => [
[
'attribute' => 'brand_name',
'value' => function($model,$key,$idx,$col){
return $model['brand_name'];
},
],
[
'class'=>'kartik\grid\EditableColumn',
'hAlign'=>'center',
'vAlign'=>'middle',
'value' => function($model,$key,$idx,$col){
return 100;
},
'editableOptions' => [
'name' => 'Test',
'header' => 'Test22',
'inputType' => Editable::INPUT_TEXT,
'formOptions' => ['action' => ['/book/editbook']],
'options' => [
'convertFormat'=>true,
'pluginOptions' => ['format' => 'php:Y-m-d']
]
]
],
Maybe you should try to set HTML with containerOptions or contentOptions attribute in editableOptions.

Automatically refreshing yii2 grid after server database changes

I have a grid that involves truck verification. I would like the contents of the grid to change without page refresh.
Currently this works when the page is refreshed but i would like it to work even when a page is not refreshed that is when the content changes in the server database.
This is the grid
<?php
$gridColumns = [
['class' => 'kartik\grid\SerialColumn'],
'reg_no',
[
'attribute'=>'truck_category',
'value'=>'truckCategory.category'
],
[
'class' => 'kartik\grid\ActionColumn',
'vAlign'=>'middle',
'urlCreator' => function($action, $model, $key, $index) { return '#'; },
'viewOptions'=>['title'=>"vdgdv", 'data-toggle'=>'tooltip'],
'updateOptions'=>['title'=>"update", 'data-toggle'=>'tooltip'],
'deleteOptions'=>['title'=>"delete", 'data-toggle'=>'tooltip'],
]
];
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => $gridColumns,
'containerOptions' => ['style'=>'overflow: auto'], // only set when $responsive = false
'beforeHeader'=>[
[
'options'=>['class'=>'skip-export'] // remove this row from export
]
],
'toolbar' => [
[],
'{export}',
'{toggleData}'
],
'pjax' => true,
'bordered' => true,
'striped' => false,
'condensed' => false,
'responsive' => true,
'hover' => true,
'floatHeader' => true,
'showPageSummary' => true,
'panel' => [
'type' => GridView::TYPE_PRIMARY
],
]);
?>
This is the controller that renders the grid
public function actionTrackingcenter()
{
$query = Truck::find()->where(['truck_status'=>5]);
$searchModel = new TruckSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams,$query);
return $this->render('trackingcenter/index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Could someone give a direction on how i can achieve the automatic change
You can use below with set-time-interval with jQuery
<?php
$this->registerJs('
setInterval(function(){
$.pjax.reload({container:"YOUR_PJAX_CONTAINER_ID"});
}, 10000);', \yii\web\VIEW::POS_HEAD);
?>
This code will be place after your GridView code
This will be reload your Pjax grid every 10 second

Yii2 kartik grid export all columns

I am using kartik grid and want to export all columns present in my table.
Problem is that i want to show only few columns in grid but download all columns in csv file.
Is it possible?
My code
<?php
$gridColumns = [
['class' => 'kartik\grid\SerialColumn'],
[
'class' => 'kartik\grid\EditableColumn',
'attribute' => 'Name',
'vAlign'=>'middle',
'headerOptions'=>['class'=>'kv-sticky-column'],
'contentOptions'=>['class'=>'kv-sticky-column'],
'editableOptions'=>['header'=>'Name', 'size'=>'255'],
'format'=>'text',
],
[
'attribute' => 'Description',
'vAlign'=>'middle',
'headerOptions'=>['class'=>'kv-sticky-column'],
'contentOptions'=>['class'=>'kv-sticky-column'],
'format'=>'text',
],
['class' => 'kartik\grid\DataColumn',
'attribute' => 'image',
'format' => 'html',
'value' => function($model, $key, $index, $column) {
return Html::img('http://localhost/demo/basic_demo/web/www/img/'.$model->image, ['class' => 'abc','width'=>70,'height'=>70]);
},
],
[
'class'=>'kartik\grid\BooleanColumn',
'attribute'=>'Status',
'vAlign'=>'middle',
],
[
'class' => 'kartik\grid\ActionColumn',
'dropdown' => true,
'vAlign'=>'middle',
'viewOptions'=>['title'=>'viewMsg', 'data-toggle'=>'tooltip'],
'updateOptions'=>['title'=>'updateMsg', 'data-toggle'=>'tooltip'],
'deleteOptions'=>['title'=>'deleteMsg', 'data-toggle'=>'tooltip'],
],
[
'class' => '\kartik\grid\ExpandRowColumn',
'header' => '',
'value' => function ($model, $key, $index) {
return GridView::ROW_COLLAPSED;
},
'detailUrl' =>Url::to(['expenses/viewdetail']),
],
];
echo GridView::widget([
'dataProvider'=> $dataProvider,
'filterModel' => $searchModel,
'columns' => $gridColumns,
'autoXlFormat'=>true,
'responsive'=>true,
'hover'=>true,
'condensed'=>true,
'floatHeader'=>true,
'bordered'=>true,
'toolbar'=>['{export}',
'{toggleData}',],
'showPageSummary'=>true,
'panel'=>[
'heading'=>'<h3 class="panel-title"><i class="glyphicon glyphicon-globe"></i> '. Html::encode($this->title).'</h3>',
'type'=>'primary',
'before'=>Html::a('<i class="glyphicon glyphicon-plus"></i>Create Expenses', ['create'], ['class' => 'btn btn-primary']),
'showFooter'=>false
],
'pjax'=>true,
'export'=>[
'fontAwesome'=>true,
'showConfirmAlert'=>false,
'target'=>GridView::TARGET_BLANK,
],
]);
?>
You can do like this in your gird column list add all column and set 'hidden' => true property which you don't want to show in grid-view but this column comes in your csv when you export csv. suppose for example here i am showing you for one column you can implement for this thing all columns. check below example code.
[
'attribute' => 'Description',
'vAlign'=>'middle',
'headerOptions'=>['class'=>'kv-sticky-column'],
'contentOptions'=>['class'=>'kv-sticky-column'],
'hidden' => true,
'format'=>'text',
],
now what happen description column will not display in gird view but it is present in exported file. i hope it is helpful for you.
On columns you my add attribute hiddenFromExport => true
For example:
'columns' => [
[
'attribute' => 'inn',
'format' => 'text',
'hiddenFromExport' => true,
],
],
It's best you pass a different array with the full grid columns rather than just the normal $gridColumns used on the web page. To keep it tidy, I have two functions in my $searchModel, one for grid columns and another for export columns. Then when setting your export menu, just call the function that returns your columns:
ExportMenu::widget([
'dataProvider' => $dataProvider,
'columns' => $searchModel->getExportColumns(),
...
]);
In your search model:
public function getGridColumns(){
return [
// page columns
];
public function getExportColumns(){
return [
// export columns
];

click yii2 gridview linkpager's page no, jump error

the gridview if on right of the page,left is some menus,when click on page no 2,it dose not only refresh the gridview,but all page including left part are lost——a totally new page come out!help~
there is the debugging Screenshot:
my action is
public function actionList()
{
$model = new Loan();
$dataProvider = new ActiveDataProvider([
'query' => $model->find(),
'pagination' => [
'pagesize' => '1',
],
]);
return $this->renderPartial('list', ['model' => $model, 'dataProvider' => $dataProvider]);
}
my view is:
<?php
use yii\grid\GridView;
use yii\grid\SerialColumn;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\LinkPager;
?>
<?=GridView::widget([
'dataProvider' => $dataProvider,
'layout'=> '{items}{pager}',
'columns' => [
['attribute' =>'loan_type','label'=>'借款类型','options' => ['width' => '80']],
['attribute' =>'amount','label'=>'金额','options' => ['width' => '80']],
['attribute' =>'rate','label'=>'还款利率','options' => ['width' => '80']],
['attribute' =>'fee','label'=>'手续费','options' => ['width' => '80']],
['attribute' =>'status','label'=>'状态','options' => ['width' => '80'] ],
['attribute' =>'comment','label'=>'审核意见','options' => ['width' => '80']],
['attribute' => 'created_at','value' =>function($model){return date('Y-m-d',strtotime($model->created_at));},'label'=>'申请时间','options' => ['width' => '150']],
[
'class' => 'yii\grid\ActionColumn',
'header' => '操作',
'template' => '{audit}',
'buttons' => [
'audit' => function ($url,$model) {
return Html::a('<span id="xxxx" class="glyphicon glyphicon-user"></span>','#',['title'=>'审核',
'onclick'=>"
$.ajax({
type: 'GET',
dataType: 'text',
url: 'http://182.92.4.87:8000/index.php?r=loan/pj', //目标地址
error: function (XMLHttpRequest, textStatus, errorThrown) {alert(XMLHttpRequest.status + ':' + XMLHttpRequest.statusText); },
success: function (page)
{
$('.ucRight').html(page);
}
});
return false;",
]);},
],
'urlCreator' => function ($action, $model, $key, $index) {
return Yii::$app->getUrlManager()->createUrl(['loan/list','id' => $model->status]);
},
'headerOptions' => ['width' => '80'],
],
],
]);
?>
The reason for your problem is that you haven't prevented the html link from directing to a new page, so your user is clicking on the link, which then loads a new page with the contents returned by the server; in this case a page of information with no layout applied. You need to add event.preventDefault() before the ajax call to stop this behaviour.
However, as #arogachev said, if you simply want to use pagination without a page refresh, then just use pjax. That is what pjax is designed for,

Yii GroupGridView buttons

I use this extension(GroupGridView) in my yii project.
Now, I need help. How to add crud buttons for the grouped elements, to get something like this:
I don't really know is it right sollution.
I've created component GroupButtonColumn:
class GroupButtonColumn extends CButtonColumn {
public $name = 'buttons';
public $value; }
And my view
$this->widget('ext.groupGridView.GroupGridView', array(
'dataProvider' => $model->search(),
'summaryText' => false,
'filter' => $model,
'mergeColumns' => ['t_id', 'buttons'],
'columns' => [
[
'name' => 't_id',
'header' => '№',
'value' => 'CHtml::link($data->t_id, ["/task/view", "id"=>$data->t_id])',
'filter' => false,
'type' => 'raw'
],
/* ... */
[
'class' => 'GroupButtonColumn',
'template' => '{update}, {delete}',
'buttons' => [
'update' => [
'url' => '$this->grid->controller->createUrl("/task/update", array("id"=>$data->t_id))'
],
'delete' => [
'url' => '$this->grid->controller->createUrl("/task/delete", array("id"=>$data->t_id))'
]
]
],
],
));
Try this way:
'mergeColumns' => array('project_id', 'project_id')
/* ... */
'columns' => [
'project_id',
'id',
/* ... */
[
'name' => 'project_id',
'header' => 'Action',
'type'=>'raw',
'value' => function($data){
return 'Start';
}
],