gpt4 book ai didi

php - 在 yii2 中验证 parent_id

转载 作者:搜寻专家 更新时间:2023-10-31 21:24:45 25 4
gpt4 key购买 nike

您好,我在验证时遇到问题,我正在使用 yii2 高级应用程序。

我在创建菜单时有一个 parent_id,我给出菜单名称并提供该菜单是否为父菜单的天气,如果父菜单复选框被选中,如果没有,则将从下拉菜单中选择一个菜单。

问题是,如果根据规则在模型中按要求设置此父 ID,则在 View 中复选框和下拉列表都将验证并且都将显示为必需。但我只想要其中任何一个。如果我没有按要求提供,那么验证本身就不会发生。请参见下图。
In this both check-box and drop-down is required.

这是我的事件表格..

   <?= $form->field($model, 'parent_id')->checkbox(array( 
'id'=>'new',
'value'=>'0',
'labelOptions'=>array('style'=>'padding:5px;'),
'disabled'=>false
)); ?>

<div class="select" id="select">
<?= $form->field($model,'parent_id')->widget(Select2::classname(), [
'data' => $menu,
'options' => ['placeholder' => 'Select a Menu name ...'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>

如果它们都留空,我希望进行验证。请告诉我任何解决方案。

最佳答案

首先,如果我确实正确理解了您的要求,为了获得更清晰的代码,我会建议为您的 model 类引入一个新的虚拟属性,而不是为同一属性分配不同值的 2 个字段:

$form->field($model,'is_parent')->checkbox(...) // don't do 'value'=>'0' here. it will be auto mapped to model virtual attribute.
$form->field($model,'parent_id')->widget(...)
/*
instead of :
$form->field($model,'parent_id')->checkbox(...) // parent_id is 1 or 0 here
$form->field($model,'parent_id')->widget(...)
*/

然后应用 Conditional Validation使用 when 进入您的模型规则属性:

public $is_parent;

public function rules()
{
return [
['is_parent', 'boolean'],
// 'parent_id' is required only if the checkbox is not checked
['parent_id', 'required', 'when' => function($model) {
return !$model->is_parent;
}],
];
}

注意:链接的文档还说:

If you also need to support client-side conditional validation, you should configure the whenClient property which takes a string representing a JavaScript function whose return value determines whether to apply the rule or not.

这是预期的,因为客户端验证脚本基于您的初始规则。所以你有两个选择。您可以在 ActiveForm 中完全禁用它并改用 Ajax 验证:

<?php $form = ActiveForm::begin([
...
'enableClientValidation' => false,
'enableAjaxValidation' => true
]); ?>

或者另一种选择是将缺少的客户端相关脚本添加到您的规则中,如文档中所示,在您的情况下可能如下所示:

public function rules()
{
return [
['is_parent', 'boolean'],

['parent_id', 'required', 'when' => function($model) {
return !$model->is_parent;
}, 'whenClient' => "function (attribute, value) {
return !$('#menu-is_parent').val();
}"],
];
}
  • 请注意,我确实期待你的 formName()返回 'menu'。默认情况下,它返回模型类名称。您还可以使用浏览器的开发工具检查复选框输入并查看 Yii 分配给它的 id 是什么。

最后,如果在选中复选框时应设置特定的 parent_id 值,您可以使用 beforeSave()afterValidate()手动将其设置为您需要的任何值,例如:

public function beforeSave($insert)
{
if ($this->is_parent) $this->parent_id = $someModel->id;
return parent::beforeSave($insert);
}

关于php - 在 yii2 中验证 parent_id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38790451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com