【问题标题】:Yii changing field format from modelYii 从模型中更改字段格式
【发布时间】:2015-02-21 00:19:08
【问题描述】:

我已按照 Yii2 指南尝试使用 Country 控制器。我在名为area 的数据库中添加了一个字段,该字段将是国家/地区。在 Country 模型中,我使用了 afterFind 事件,如下所示:

public function afterFind()
    {
      if ($this->area == NULL){
        //$this->area-> What Could I do here?!!
        $this->area = 'N/A';        
      }   
      return true;
    }

如果没有区域设置为N/A,我想更改区域的默认值area 字段是浮动的。它在更新视图中工作正常。但是,鉴于 actionView 它返回有关格式的错误。在该视图中,我对属性进行了如下格式化:

<?= 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'],
        ],
    ]) ?>

错误是: Invalid Parameter – yii\base\InvalidParamException

“N/A”不是数值。

我的问题是:如何从模型中访问字段格式?

【问题讨论】:

    标签: php yii2


    【解决方案1】:

    我会删除后查找,您最好使用值 null 然后使用文本“N/A”

    ['attribute' => 'area', 'value' => function($model, $index, $widget){
                        return ($model->area ? Yii::$app->formatter->asDecimal($model->area) : 'N/A');
                    }],
    

    你可以像这样定义你的属性,这样就可以了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-10
      • 1970-01-01
      • 2016-10-28
      • 2014-10-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-30
      • 1970-01-01
      相关资源
      最近更新 更多