sam
sam

Reputation: 956

How to display Image in gridview yii2

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

Upvotes: 1

Views: 7176

Answers (3)

Bhatt Akshay
Bhatt Akshay

Reputation: 159

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']);
     },
],

Upvotes: 3

Farshid
Farshid

Reputation: 518

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'];

Upvotes: 1

Fabrizio Caldarelli
Fabrizio Caldarelli

Reputation: 3008

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']);
     }
     ],

Upvotes: 0

Related Questions