Reputation: 13534
I have followed Yii2 guide and try to play with Countries controller. I added a field to the database named area
which is going to be the country area. In Country
model I used afterFind event like the following:
public function afterFind()
{
if ($this->area == NULL){
//$this->area-> What Could I do here?!!
$this->area = 'N/A';
}
return true;
}
I want to change the default value of area if there is no area has been set to be N/A
the area
field is float. It works fine in the update view. However, in view of actionView it returns errors about formatting. In that view I have made format to the attributes as follows:
<?= DetailView::widget([
'model' => $model,
'attributes' => [
['attribute' => 'code','format' => 'raw','value' => "{$model->code} <img style=\"box-shadow:0 0 5px #0099ff\" src=\"flags/".strtolower($model->code).".png\" />"],
'name',
['attribute' => 'population', 'format' => 'decimal'],
['attribute' => 'area', 'format' => 'decimal'],
],
]) ?>
The error is: Invalid Parameter – yii\base\InvalidParamException
'N/A' is not a numeric value.
My question is: How to access the field format from model?
Upvotes: 0
Views: 887
Reputation: 9357
I would remove the after find, you are better of working with the value null then with the text 'N/A'
['attribute' => 'area', 'value' => function($model, $index, $widget){
return ($model->area ? Yii::$app->formatter->asDecimal($model->area) : 'N/A');
}],
You can define your attribute like this and that should do the trick.
Upvotes: 2