我有一个模型类,我在很多视图中使用它。
class Translations extends CActiveRecord
{
...
public function attributeLabels()
{
return array(
'row_id' => 'Row',
'locale' => 'Locale',
'short_title' => 'Short Title',
'title' => 'Title',
'sub_title' => 'Sub Title',
'description' => 'Description',
'content1' => 'Content1',
'content2' => 'Content2',
'com_text1' => 'Com Text1',
'com_text2' => 'Com Text2',
'com_text3' => 'Com Text3',
'com_text4' => 'Com Text4',
'com_text5' => 'Com Text5',
'com_text6' => 'Com Text6',
);
}
...
}
我可以为每个视图更改模型属性标签值吗?
答案 0 :(得分:1)
您可以根据您要使用的视图声明模型的场景,并根据场景定义参数?让我们说你的不同观点适用于不同的人:
public function attributeLabels()
{
switch($this->scenario)
{
case 'PersonA':
$labels = array(
...
'myField' => 'My Label for PersonA',
...
);
break;
case 'PersonB':
$labels = array(
...
'myField' => 'My Label for PersonB',
...
);
break;
case 'PersonC':
$labels = array(
...
'myField' => 'My Label for PersonC',
...
);
break;
}
return $labels;
}
然后在您的控制器中为每个人定义场景,例如;
$this->scenario = 'PersonA';
然后在声明“PersonA”作为场景后的视图中,您会看到myField
的标签为“我的PersonA标签”
答案 1 :(得分:0)
没有允许您以官方方式更改属性标签的方法或变量,因此,我建议您扩展模型以支持它。
在CActiveRecord中,您可以定义一个名为attributeLabels的字段和一个名为setAttributeLabels的方法,并覆盖attributeLabels方法。
protected $attributeLabels = [];
public function setAttributeLabels($attributeLabels = []){
$this->attributeLabels = $attributeLabels;
}
/**
* @inheritDoc
*
* @return array
*/
public function attributeLabels(){
return array_merge(parent::attributeLabels(), $this->attributeLabels);
}
并且从\ yii \ base \ Model :: attributeLabels的文档中说
注意,为了继承在父类中定义的标签,子类需要使用
array_merge()
之类的功能将父标签与子标签合并。
因此,在Translations类中,您应该合并父类的属性标签,例如CActiveRecord类。因此,CActiveRecord attributeLabels方法应如下所示:
public function attributeLabels(){
return array_merge([
'row_id' => 'Row',
'locale' => 'Locale',
'short_title' => 'Short Title',
'title' => 'Title',
'sub_title' => 'Sub Title',
'description' => 'Description',
'content1' => 'Content1',
'content2' => 'Content2',
'com_text1' => 'Com Text1',
'com_text2' => 'Com Text2',
'com_text3' => 'Com Text3',
'com_text4' => 'Com Text4',
'com_text5' => 'Com Text5',
'com_text6' => 'Com Text6',
], parent::attributeLabels());
}