更改模型属性标签

问题描述 投票:0回答:2

我有一个模型类,并且在很多视图中都使用它。

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',         
        );
    }
...
}

我可以更改每个视图的模型属性标签值吗?

php yii
2个回答
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的标签”


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());
}
© www.soinside.com 2019 - 2024. All rights reserved.