【问题标题】:Laravel Form Model Binding overriding default valueLaravel 表单模型绑定覆盖默认值
【发布时间】:2015-04-06 00:59:11
【问题描述】:

我有一个多对多关系,并且正在构建一个表单来启用更新。

使用一系列复选框设置关系。

模型为PostCategory,并定义了传统的mtm 关系。

在我的编辑帖子表单中,我获得了一个类别列表,并将当前选择的类别急切地加载到我的帖子模型中。表单如下所示:

{!! Form::model($post, ['route' => ['admin.posts.update', $post->id], 'method' => 'PATCH']) !!}

// .. some fields

@foreach ($categoryList as $categoryId => $category)
    <div class="checkbox">
    <label>
    {!! Form::checkbox('category[]', $categoryId, in_array($categoryId, $selected_categories)) !!} {{ $category }}
    </label>
    </div>
@endforeach

所选类别的定义如下:

$selected_categories = $post->categories->lists('id');

...它给出了一个简单的数组,仅包含相关类别的 id。

这会导致默认选中所有类别复选框,尽管 in_array($categoryId, $selected_categories)) 语句仅在类别 ID 相关时才会评估为 true。如果我将复选框的第一个(名称)参数更改为 category[] 以外的其他参数,则它们会被正确检查。

为什么表单模型绑定会检查所有复选框,为什么即使我尝试通过将第三个参数传递给复选框来覆盖它,它也没有效果?

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    Illuminate 的 FormBuilder 的生成复选框方法中似乎存在错误。当您将多选元素 (category[]) 传递给该方法时,它会在该数组中查找单词“on”,当然,即使您只检查并发布,它也会为它生成的每个复选框找到它一个复选框。

    protected function getCheckboxCheckedState($name, $value, $checked) {
        if (isset($this->session) && ! $this->oldInputIsEmpty() && is_null($this->old($name))) return false;
        if ($this->missingOldAndModel($name)) return $checked;
        $posted = $this->getValueAttribute($name);
    
        return is_array($posted) ? in_array($value, $posted) : (bool) $posted;
    }
    

    假设您只选中了一个复选框。已发布的复选框数组:

    checkbox[0]
    checkbox[1]
    checkbox[2]
    checkbox[3] = 'on'     // only value that is ever posted
    checkbox[4]
    checkbox[5]
    

    数组如下所示:array('checkbox' =&gt; [3 =&gt; 'on'])

    因此in_array('on', [3 =&gt; 'on']) 将为所有复选框返回true

    【讨论】:

    • 嗯,这是应该发布错误报告的原因吗?我可能会这样做。
    • 但我还是有点困惑这是否真的如此。复选框的名称应该与您是否要检查它无关......
    • 好吧,我将复选框命名为categories[],因为这是我正在更新的属性。当然,我可以将其命名为 postCategories[] 之类的其他名称,然后只需手动同步更新时的关系。例如。 $post-&gt;categories-&gt;sync($request-&gt;get('postCategories')); 但这似乎是一种不优雅的方式。
    • 看来我不是第一个遇到这种情况的人。 PR 已提交但已关闭:github.com/laravel/framework/issues/5078
    • 您找到解决方案了吗?
    猜你喜欢
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    相关资源
    最近更新 更多