yii 更改模型属性标签

weylhg0b  于 2022-11-09  发布在  其他
关注(0)|答案(2)|浏览(118)

我有一个模型类,我在许多视图中使用它。

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

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

1aaf6o9v

1aaf6o9v1#

你可以根据你要使用的视图为模型声明一个场景,并根据场景定义参数。假设你的不同视图是针对不同的人的:

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的标签为“My Label for PersonA”

kgqe7b3p

kgqe7b3p2#

没有方法或变量允许你以正式的方式改变属性标签,所以我建议你扩展模型来支持它。
在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());
}

相关问题