4

How to set attribute labels when using dynamic model in yii2 framework?

Here is my code below:

$model = DynamicModel::validateData(compact('name','shipping'), [
        [['name','shipping'], 'required'],
    ]);
    if ($model->hasErrors()) {
        // validation fails
      //  }
    } else {
        //validation true
    }
1
  • 1
    Hmm, looks like this is not possible as attributeLabels() is only a getter, not a setter. There was a (closed) issue on GitHub requesting such a feature; the comments suggest implementing your own MyDynamicModel class which allows for setting attribute labels. github.com/yiisoft/yii2/issues/6420 Commented Sep 14, 2015 at 19:14

3 Answers 3

6

As a simple way out, just set separate validation messages for needed attributes:

$model = DynamicModel::validateData(compact('name','shipping'), [
    [['name'], 'required', ['message' => Yii::t('app', 'Name is required for this form.')]],
    [['name'], 'required', ['message' => Yii::t('app', 'Shipping address is required for this form.')]],
]);

And use labels when outputting DynamicModel field:

echo $form->field($model, 'name')->textInput()->label(Yii::t('app', 'Name')); 
echo $form->field($model, 'name')->textInput()->label(Yii::t('app', 'Shipping address'));
Sign up to request clarification or add additional context in comments.

Comments

0

I like to extend the component, like this:

class DynamicModel extends \yii\base\DynamicModel {

    protected $_labels;

    public function setAttributeLabels($labels){
        $this->_labels = $labels;
    }

    public function getAttributeLabel($name){
        return $this->_labels[$name] ?? $name;
    }
}

And, to use it:

$attributes = ['name'=>'John','email'=>'[email protected]'];
$model = new DynamicModel($attributes);
$model->setAttributeLabels(['name'=>'Name','email'=>'E-mail']);
$model->validate();

1 Comment

There is no need, both methods, available since version yii 2.0.35
-2

For example:

model

    public function attributeLabels()
    {
       return [
         'id' => Yii::t('app', 'ID'),
         'first_name' => Yii::t('app', 'First Name'),
      ];
   }

For more on attributeLabels() and generateAttributeLabel()

1 Comment

The OP is not asking that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.