我开始学习 Laravel,并且仍在学习曲线上。现在我从 Laravel 3 开始,但一旦我开始工作,很可能会将我的项目切换到 Laravel 4。
现在的问题是,如何验证复选框数组,我想验证组内至少有 1 个复选框已启用(选中)。我在 Laravel 论坛上的某个地方读到,我们只是使用必需的方法来验证它们,但是当我dd(input::all())
我没有看到其他任何内容,但输入字段和复选框不是其中的一部分......
我的 Blade 的一部分为复选框创建代码:
<label class="checkbox">{{ Form::checkbox('changeReasons[]', 'ckbCRCertification', Input::had('ckbCRCertification'), array('id' => 'ckbCRCertification')) }} Certification</label>
<label class="checkbox">{{ Form::checkbox('changeReasons[]', 'ckbCRDesignCorrection', Input::had('ckbCRDesignCorrection'), array('id' => 'ckbCRDesignCorrection')) }} Design Correction</label>
我的控制器(REST)代码是:
public function post_create()
{
print "Inside the post_create()";
// validate input
$rules = array(
'ecoNo' => 'min:4',
'productAffected' => 'required',
'changeReasons' => 'required'
);
$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
{
return Redirect::back()->with_input()->with_errors($validation);
}
$eco = new Eco;
$eco->ecoNo = Input::get('ecoNo');
$eco->productAffected = Input::get('productAffected');
$eco->save();
return Redirect::to('ecos');
}
我还想知道验证失败后获取复选框状态的正确代码,我想我看到了Input::had(checkBoxName)
某处,但这似乎不起作用,我可能没有正确使用它,而且我对此有点困惑,因为我看到的所有示例都是用于输入而没有其他内容。我假设 L4 中的验证大致相同,是吗?
回顾这个项目并进行更多研究,我发现解决这个问题的最佳方法如下。
我的刀片视图:
<div class="control-group row-fluid">
<?php $arrChangeReasons = Input::old('changeReasons', array()); // array of enable checkboxes in previous request ?>
<label class="checkbox">{{ Form::checkbox('changeReasons[]', 'certification', in_array('certification', $arrChangeReasons)) }} Certification</label>
<label class="checkbox">{{ Form::checkbox('changeReasons[]', 'designCorrection', in_array('designCorrection', $arrChangeReasons)) }} Design Correction</label>
</div>
刀片视图的解释分为两个步骤,验证发生后,如下:
- 拉取复选框数组(在我的例子中为“changeReasons[]”)
Input::old
- 然后,我们可以从该数组中搜索单个复选框并查看它们是否在那里,如果存在,则将复选框更改为
checked
状态。这就是 in_array() 函数的工作,返回 true/false 将更改复选框的状态。
我的控制器(REST)代码与我一开始的问题中所写的完全相同。有关更多信息,定义$rules = array('changeReasons' => 'required');
将确保至少有 1 个复选框checked
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)