Yii2 GridView列数据作为相关表属性的链接

时间:2015-08-13 14:14:30

标签: php gridview yii2

我想让GridView在url链接类型中有一列。这一列来自模型Region中的关系(作为region_type - FK),特别是此相关表的名称属性。在这个GridView中,获取这些相关表的名称值没有问题,但问题是将它们作为链接格式而不是普通名称提供。我在RegionSearch模型中将parentRegion.name设置为关系属性。

查看

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            [
                'label' => 'View parent',
                'format' => 'raw',
                // here comes the problem - instead of parent_region I need to have parent
                'value' => function ($dataProvider) {
                     return Html::a('view', '/admin/region/view?id=' . $dataProvider->parent_region);
                 },
            ],

            'parentRegion.name',  // this is what I want to display in link value - name of this related data


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

RegionSearch

public function attributes()
{
            // add related fields to searchable attributes
            return array_merge(parent::attributes(), ['parentRegion', 'regionType']);
}

public function search($params)
{
    $query = Region::find();

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    $query->joinWith(['parentRegion' => function($query) { $query->from(['parentRegion' => 'region']); }]);
    $dataProvider->sort->attributes['parentRegion'] = [
        'asc' => ['parentRegion' => SORT_ASC],
        'desc' => ['parentRegion' => SORT_DESC],
    ];

    $this->load($params);

    if (!$this->validate()) {
        // uncomment the following line if you do not want to return any records when validation fails
        // $query->where('0=1');
        return $dataProvider;
    }

    $query->andFilterWhere(['like', 'name', $this->name])
        ->andFilterWhere(['like', 'parentRegion', $this->getAttribute('parentRegion')])

    return $dataProvider;
}

您能否帮助我如何将此属性名称(相关表格的属性)作为链接获取此GridView

2 个答案:

答案 0 :(得分:3)

试试这个..

  [
           'label' => 'Name',
           'format' => 'raw',
           'value' => function ($data) {
                         return Html::a($data->parentRegion->name, ['/admin/region/view', 'id' => $data->parent_id]);
                     },
    ],

答案 1 :(得分:0)

这对我有用

'format' => 'raw',
'value' => function($data){return Html::a(Html::encode($data->country->name), ['country/view','id' => $data->countryid], ['data-pjax' => 0]);}