[英]Yii changing field format from model
I have followed Yii2 guide and try to play with Countries controller. 我遵循了Yii2指南,并尝试使用“国家/地区”控制器。 I added a field to the database named area
which is going to be the country area. 我在名为area
的数据库中添加了一个字段,该字段将成为国家/地区。 In Country
model I used afterFind event like the following: 在Country
模型中,我使用了afterFind事件,如下所示:
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. 如果没有区域设置为N/A
而area
字段为float,则我想更改区域的默认值。 It works fine in the update view. 它在更新视图中正常工作。 However, in view of actionView it returns errors about formatting. 但是,鉴于actionView,它返回有关格式化的错误。 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 错误是:无效的参数– yii \\ base \\ InvalidParamException
'N/A' is not a numeric value. “ N / A”不是数字值。
My question is: How to access the field format from model? 我的问题是:如何从模型访问字段格式?
I would remove the after find, you are better of working with the value null then with the text 'N/A' 我会删除之后的查找,您最好使用null值,然后使用文本“ 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. 您可以像这样定义属性,这应该可以解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.