Barry Smith
Barry Smith

Reputation: 105

Refer to Yii2 ActiveRecord / model column in GridView?

I am trying to get this stackoverflow code (URL in yii2 gridview) actually tied to displaying Last_Name from my Contact record and actually generating a mailto: link when the Last_Name is clicked.

My code displays static text and a static link but I don't know how to properly reference the active record.

I also don't want to do a "find" and essentially do a subquery ... it seems that would be very wasteful.

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

        //'contact_id',
        'contact_frequency',

        [
            'label' => 'Last Name',
            'format' => 'raw',
            'value' => function ($data) {
                return Html::a(Html::encode('replace with $contact->last_name'),'replace with $contact->email1:email');
            },
        ],

        'first_name',
        // 'title',
        'email1:email',
        'last_touch_date',
        'last_contact',
        ['class' => 'yii\grid\ActionColumn', 'template' => '{view}'], 
    ],
]); ?>

Upvotes: 1

Views: 858

Answers (2)

Barry Smith
Barry Smith

Reputation: 105

For those newbies like me. It appears $data is the ActiveRecord in question.

return Html::a(Html::encode($data->last_name), 'mailto:' . $data->email1);

Upvotes: 0

arogachev
arogachev

Reputation: 33548

Since the text and the link are different you can't use built-in email formatter.

But Yii 2 Html helper has special method mailto() for handling this so I recommend using it instead of manually constructing the link.

Email formatter also calls this helper but with the same text and email.

In that case the code will be:

use yii\helpers\Html;

...

[
    'label' => 'Last Name',
    'format' => 'raw',
    'value' => function ($model) {
        return Html::mailto($model->last_name, $model->email);
    },
],

Upvotes: 2

Related Questions