[英]Yii2 - Validate attribute with keys
I have a problem with attribute key validation.我对属性键验证有疑问。
In model I have property like:在 model 我有如下属性:
public $_fileds = [];
and My view和我的看法
<?= $form->field($model, '_fileds[name]') ?>
<?= $form->field($model, '_fileds[type]') ?>
I want to set "_fields[name]" as requierd field.我想将“_fields [name]”设置为必需字段。 For example I tried add to rules in model something like this:
例如,我尝试在 model 中添加规则,如下所示:
public function rules()
{
return [
[['_fields[name]'], 'required']
];
}
but this not working:(但这不起作用:(
Does anyone have any solution?有没有人有任何解决方案?
Sorry for my not good English and thanks in advance for all solutions.对不起,我的英语不好,并提前感谢所有解决方案。
You can write your own validation.您可以编写自己的验证。
Remove: public $_fileds = [];
删除:
public $_fileds = [];
public function rules()
{
return [
[['_fields[name]'], 'validateName']
];
}
In same model class:在相同的 model class 中:
public function validateName():bool
{
... your checks(if fails return false) ...
return true;
}
But there is one issue: if some of checks fails you, in normal cases, need to set error message using $this->addError() which will correctly work with attributes which are not array elements because as first element of $this->addError()
you need to pass attribute name as string where '_fileds' is ok but '_fileds[name]' won't work.但是有一个问题:如果某些检查失败,在正常情况下,您需要使用 $this->addError() 设置错误消息,这将正确处理不是数组元素的属性,因为作为
$this->addError()
的第一个元素$this->addError()
您需要将属性名称作为字符串传递,其中 '_fileds' 可以,但 '_fileds[name]' 不起作用。 So you also need to find a way to return errors if they appear.因此,您还需要找到一种在错误出现时返回错误的方法。 Same issue with attribute labels and hints.
属性标签和提示的问题相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.