How to put an image in GridView in yii2?I have the following code. But its not displaying the image as it is not giving any image url. Where to put the image url?
<?php echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'c_id',
'name:ntext',
'description:ntext',
'logo:image',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
In views->image->index.php
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute'=>'image_path',
'label'=>'Image',
'format'=>'html',
'content' => function($data){
$url = $data->getParentName();
return Html::img($url, ['alt'=>'yii','width'=>'250','height'=>'100']);
}
],
'caption1',
'caption2',
'status',
['class' => 'yii\grid\ActionColumn'],
],
'tableOptions' =>['class' => 'table table-striped table-bordered'],
]); ?>
In model->image
public function getParent()
{
return $this->hasOne(Image::className(), ['image_id' => 'image_id']);
}
public function getParentName()
{
$model=$this->parent;
return $model?$model->image_path:'';
}
table attributes are, image_id,image_path,caption1,caption2,status
Try like,
array(
'format' => 'image',
'value'=>function($data) { return $data->imageurl; },
),
And in your model,
public function getImageurl()
{
return \Yii::$app->request->BaseUrl.'/<path to image>/'.$this->logo;
}
Don't know this is the right way or not.But this works for me.
You can also use:
public function getImageurl()
{
return \Yii::$app->urlManager->createUrl('@web/path/to/logo/'.$this->logo);
}
'@web' is a predefined path aliases.
'urlManager->CreateUrl()' do something more than resolving aliases.
It is simple you can just declare it in your index file as below.
[
'label' => Your Label Here',
'format' => 'raw',
'value' => function ($data) {
$images = '';
$images = $images.Html::img(\Yii::$app->request->BaseUrl.'/your-path-here/'.$date->getImagefilename(),['alt'=>'','width'=>'30','height'=>'30', 'data-toggle'=>'tooltip','data-placement'=>'left','title' => $name->pictogram_comment ,'style'=>'cursor:default;']);
return ($images);
}
],
You will have to get image instance from your model. If required example please comment, will get back on that.
You can try this one:
<?= GridView::widget
([
'dataProvider' => $dataProvider,
'filterModel' => $searchdata,
'columns' => [
[
'attribute' => 'logo',
'format' => 'html',
'label' => 'Image',
'value' => function ($data) {
return Html::img('/advanced/hello/frontend/web/image/' . $data['logo'],
['width' => '80px',
'height' => '80px']);
},
],
],
]);
?>