Image in gridview in yii2

2019-01-22 23:07发布

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',
        array(
                'format' => 'image',
               'attribute'=>'logo',

),

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

8条回答
家丑人穷心不美
2楼-- · 2019-01-22 23:30

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

查看更多
SAY GOODBYE
3楼-- · 2019-01-22 23:34

I used to use 'raw' format for this type of work.

[
    "attribute": "image",
    "format": "raw",
    "value": function($model){
        return ($model->image) ? Html::img("/path-to-img-location" . $model->image) : false;
    }
]

if image exists then image is displayed otherwise it is blank.

查看更多
登录 后发表回答