简体   繁体   中英

Yii changing field format from model

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM