I am want to get relational table field value in View,But the relational table maybe have not corresponding data.Can I use some method to replace the php code in Yii2 View?
// $model->relationTable maybe is null
<?= isset($model->relationalTable)?$model->relationalTable->field:'' ?>
I hope $model->relationalTable->field
can work when $model->relationalTable
is null.I wantn't a lot of if condition
in view.
example:
in Model class:
public function getUser()
{
return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
}
Use:
$customers = Customer::find()
->joinWith('user')
->one();
Access:
$customers->user->id;
See the documentation here
Since you are having issue in view page, I am assuming your question is related to displaying data in DetailView widget. Below is the code sample:
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'vehicle_id',
[
'attribute' => 'maker',
'label' => 'Maker Details',
],
[
'attribute' => 'user_id',
'label' => 'Assigned To',
'format' => 'raw',
'value' => function ($model) {
$value = isset($model->user->name) ? $model->user->name : NULL;
return $value;
},
],
],
]) ?>
If you have implemented ACL or RBAC, you can further refine your code as shown below:
[
'attribute' => 'user_id',
'label' => 'Assigned To',
'format' => 'raw',
'value' => function ($model) {
$value = isset($model->user->name) ? $model->user->name : NULL;
$id = isset($model->user_id) ? $model->user_id : NULL;
if($value && $id){
if(Yii::$app->user->can('user/view')){
$value = Html::a($value, ['user/view', 'id' => $id], ['class' => '']);
}
}
return $value;
},
],
Hope this help. Or give some more information/code to help understand your issue.
If you just want to simplify this code, you can use ??
operator:
<?= $model->relationalTable->field ?? '' ?>
If you need to encode it:
<?= Html::encode($model->relationalTable->field ?? '') ?>
Alternatively you may create helper method, which will do such check for you, and then call it in this way:
<?= $model->getRelationalTableField() ?>
But if you can do this, probably the best option is to configure foreign key constraint for related record at DB level, so database will ensure that related record always exist - you don't need any checks then.