Yii Framework Forum

Global Attribute Labels


(DBCreator) #1

I was wondering if there was a way to setup global attribute labels.

Say for instance an attribute for Region, I have it in a reference table (PK), and then a multitude of other tables (FK - contacts, projects, …). Now, instead of defining the label in each model, I was wondering if there was an approach to create a global attribute label, so there would only be one place to edit to update the entire application rather than needing to edit multiple model files. Just an idea and curious if it had ever been done before.

Thank you in advance for your insight into the matter.


(Mehdi Achour) #2

Personally I wouldn’t do this, as sometime an attribute means something in a context, and something different in another. I think the best way to go around what you want is to use i18n.

Usually, I generate my models using Gii, which take care of generating the attributeLabels() method for me.
I also instruct Gii to internationalize these labels:

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('models', 'ID'),
            'reference' => Yii::t('models', 'Reference'),
            'date' => Yii::t('models', 'Date'),
        ];
    }

So later, if I want to globally rename “reference” for example, I’d do that in my en message file.

And if for some reason, “reference” doesn’t mean the same thing in two contexts, I edit one of the models and change the label for it, then re-run messages extractions.


(Mehdi Achour) #3

PS: There’s no harm in using i18n, even if your source code is in English and you will only provide the English language :slight_smile:


(DBCreator) #4

Thank you for all your advice. It is greatly appreciated!