Amin Shafiee
Amin Shafiee

Reputation: 425

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

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
    }

Upvotes: 4

Views: 7657

Answers (3)

rodrigoitj
rodrigoitj

Reputation: 1

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();

Upvotes: 0

insane-dev
insane-dev

Reputation: 59

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'));

Upvotes: 6

Insane Skull
Insane Skull

Reputation: 9358

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()

Upvotes: -2

Related Questions