4

我开始学习 Laravel 并且仍在学习曲线上。现在我从 Laravel 3 开始,但一旦我开始工作,很可能会将我的项目切换到 Laravel 4。现在的问题是,如何验证复选框数组,我想验证组内至少有 1 个启用(选中)。我在 Laravel 论坛上的某个地方读到我们只是使用必需的来验证它们,但是当我dd(input::all())没有看到任何其他内容时,除了输入字段和复选框不是它们的一部分......

我的 Blade Create 复选框的一部分代码:

<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 中的验证大致相同,是吗?

4

2 回答 2

3

回到这个项目并进行更多研究,我发现解决这个问题的最佳方法如下。

我的刀片视图:

<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>

刀片视图的解释是一个 2 个步骤的过程,在验证发生后,如下所示:

  1. 拉出复选框数组(在我的情况下为'changeReasons []')Input::old
  2. 然后,我们可以从该数组中搜索单个复选框并查看它们是否在其中,如果它们存在则将复选框更改为checked状态。那是 in_array() 函数的工作,返回真/假将改变复选框的状态。

我的控制器(REST)代码与我一开始在问题中所写的完全一样。有关更多信息,定义$rules = array('changeReasons' => 'required');将确保至少 1 个复选框是checked.

于 2013-05-13T20:28:50.943 回答
0

请记住,复选框需要一个类似的值。如果 Checkbox 被选中 Input::get('foo') 将返回 1,但如果未选中它将不返回任何内容,因为它不在后数组中。

我正在使用这段代码:

if(Input::get('foo')){
    $bar->is_foo = 1;
}
else{
    $bar->is_foo = 0;
}
于 2013-05-01T23:49:47.277 回答