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

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

Here is my code below:

$model = DynamicModel::validateData(compact('name','shipping'), [
        [['name','shipping'], 'required'],
    ]);
    if ($model->hasErrors()) {
        // validation fails
      //  }
    } else {
        //validation true
    }
+4
source share
4 answers

As an easy way out, just set up separate verification messages for the required 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 displaying the 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'));
+4
source

I like to expand the component, for example:

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'=>'john@mailinator.com'];
$model = new DynamicModel($attributes);
$model->setAttributeLabels(['name'=>'Name','email'=>'E-mail']);
$model->validate();
0
source

...

attributeLabels()

....

http://www.yiiframework.com/doc-2.0/yii-base-model.html# $attributes-detail

-1

:

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

Learn more about attributeLabels () and generateAttributeLabel ()

-1
source

Source: https://habr.com/ru/post/1606586/


All Articles