DetailView中的关联属性如何在匿名函数中获取其值? [ 2.0 版本 ]
<?= DetailView::widget([
'model' => $model,
'attributes' => [
[
'attribute'=> 'user.nickname',
'label'=>'Creater',
'value'=>function($model){
return $model->'user.nickname'." ".$model->createdAt;
}
],
$model->'user.nickname',这个正确写法应该是怎样的?现在报错!谢谢
最佳答案
-
你把$model传过去就行了
'value' => $model->user->nickname." ".$model->createdAt;
前提:$model这个类需要定义user的相关属性(采用hasOne定义)
参见:http://www.yiichina.com/doc/guide/2.0/db-active-record
其他 3 个回答
-
dashixiong 回答于 2017-04-26 15:34 举报
什么啊,这是,闻所未闻。
-
johnny1991 回答于 2017-04-26 15:39 举报
源码上看起来是不支持匿名函数的,会报一个'The attribute configuration must be an array.'错误
protected function normalizeAttributes() { if ($this->attributes === null) { if ($this->model instanceof Model) { $this->attributes = $this->model->attributes(); } elseif (is_object($this->model)) { $this->attributes = $this->model instanceof Arrayable ? array_keys($this->model->toArray()) : array_keys(get_object_vars($this->model)); } elseif (is_array($this->model)) { $this->attributes = array_keys($this->model); } else { throw new InvalidConfigException('The "model" property must be either an array or an object.'); } sort($this->attributes); } foreach ($this->attributes as $i => $attribute) { if (is_string($attribute)) { if (!preg_match('/^([\w\.]+)(:(\w*))?(:(.*))?$/', $attribute, $matches)) { throw new InvalidConfigException('The attribute must be specified in the format of "attribute", "attribute:format" or "attribute:format:label"'); } $attribute = [ 'attribute' => $matches[1], 'format' => isset($matches[3]) ? $matches[3] : 'text', 'label' => isset($matches[5]) ? $matches[5] : null, ]; } if (!is_array($attribute)) { throw new InvalidConfigException('The attribute configuration must be an array.'); } if (isset($attribute['visible']) && !$attribute['visible']) { unset($this->attributes[$i]); continue; } if (!isset($attribute['format'])) { $attribute['format'] = 'text'; } if (isset($attribute['attribute'])) { $attributeName = $attribute['attribute']; if (!isset($attribute['label'])) { $attribute['label'] = $this->model instanceof Model ? $this->model->getAttributeLabel($attributeName) : Inflector::camel2words($attributeName, true); } if (!array_key_exists('value', $attribute)) { $attribute['value'] = ArrayHelper::getValue($this->model, $attributeName); } } elseif (!isset($attribute['label']) || !array_key_exists('value', $attribute)) { throw new InvalidConfigException('The attribute configuration requires the "attribute" element to determine the value and display label.'); } $this->attributes[$i] = $attribute; } }
-
阿江
注册时间:2015-10-18
最后登录:2024-03-03
在线时长:186小时21分
最后登录:2024-03-03
在线时长:186小时21分
- 粉丝94
- 金钱16816
- 威望160
- 积分20276