如何在yii2框架中使用动态模型时设置属性标签?
以下是我的代码:
$model = DynamicModel::validateData(compact('name','shipping'), [
[['name','shipping'], 'required'],
]);
if ($model->hasErrors()) {
// validation fails
// }
} else {
//validation true
}
答案 0 :(得分:4)
作为一种简单的方法,只需为所需属性设置单独的验证消息:
$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.')]],
]);
输出DynamicModel字段时使用标签:
echo $form->field($model, 'name')->textInput()->label(Yii::t('app', 'Name'));
echo $form->field($model, 'name')->textInput()->label(Yii::t('app', 'Shipping address'));
答案 1 :(得分:0)
我喜欢扩展组件,如下所示:
class DynamicModel extends \yii\base\DynamicModel {
protected $_labels;
public function setAttributeLabels($labels){
$this->_labels = $labels;
}
public function getAttributeLabel($name){
return $this->_labels[$name] ?? $name;
}
}
而且,使用它:
$attributes = ['name'=>'John','email'=>'john@mailinator.com'];
$model = new DynamicModel($attributes);
$model->setAttributeLabels(['name'=>'Name','email'=>'E-mail']);
$model->validate();
答案 2 :(得分:-1)
例如:
模型
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'first_name' => Yii::t('app', 'First Name'),
];
}
的更多信息