【问题标题】:how to update a checkbox value on update function on request based?如何根据请求更新更新功能上的复选框值?
【发布时间】:2021-01-21 12:05:52
【问题描述】:

我写了一个非常简单的代码来更新复选框的值,但是如果取消选中它在数据库中更新 1 如果请求在这里提交,它不会更新 0 是代码

<div class="form-group">
    <label>If it is checked it means user can only create given customer order.</label>
    <input type="checkbox" id="js-switch" name="customer_itself" @if($ot->customer_itself == 1) checked @endif>
</div>

控制器端

if ($request->has('customer_itself')) {
    if($ot->customer_itself == 1){
        $ot->customer_itself = 0;
    }else{
        $ot->customer_itself = 1;
    }
            

其中有什么错误?

【问题讨论】:

  • 我并不精通 laravel,但据我所知,如果我错了,请纠正我,但我认为输入没有任何价值。
  • 这是一个复选框,当我们选中它时,它会将值传递给控制器​​,表明该复选框是触发的,我接受使用 has() 而不是值的触发
  • 好的。那么请看下面的答案,这看起来很有希望。

标签: php laravel laravel-5 input checkbox


【解决方案1】:

未选中复选框的值不会作为参数传递。

$ot->customer_itself = $request->has('customer_itself');

【讨论】:

  • 在PATCH路由(REST API中使用laravel)的情况下,如果只想修改数据库中的一个字段,这个检查可能会有问题
【解决方案2】:

输入类型“复选框”未选中时不返回值。

两种解决方案可供选择:

在 PHP 中:

$ot->customer_itself = $request->has('customer_itself');

在 HTML 中:

强制第一次返回“0”以强制更新数据库。如果复选框为“1”,则此值将被覆盖:

<div class="form-group">
    <label>If it is checked it means user can only create given customer order.</label>
    <input type="hidden" name="customer_itself" value=0>
    <input type="checkbox" id="js-switch" name="customer_itself" @if($ot->customer_itself == 1) checked @endif>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 2012-08-30
    • 2014-04-26
    相关资源
    最近更新 更多