【问题标题】:In Laravel using the old helper, how to check value of old('value', 'default') when 'value' is an array and 'default' is a basic value?在使用旧助手的 Laravel 中,当 'value' 是数组且 'default' 是基本值时,如何检查 old('value', 'default') 的值?
【发布时间】:2018-01-22 23:27:30
【问题描述】:

假设我有复选框。每个都有一个在检查时进入数组的值。

<input type="checkbox" id="card_type1" name="card_type[]" value="easy" @if(old('card_type') != NULL && in_array('easy', old('card_type')) || old('foo', $parkingLot->m_plots_can_easycard) === '1') checked @endif>
<input type="checkbox" id="card_type2" name="card_type[]" value="icash" @if(old('card_type') != NULL && in_array('icash', old('card_type')) || old('foo', $parkingLot->m_plots_can_icash20) === '1') checked @endif>
<input type="checkbox" id="card_type3" name="card_type[]" value="ipass" @if(old('card_type') != NULL && in_array('ipass', old('card_type')) || old('foo', $parkingLot->m_plots_can_ipass) === '1') checked @endif>

第一次加载表单时,我想反映数据库值。如果 DB 中的值为“1”,请选中该复选框。然后我修改复选框 - 选中一些并取消选中一些 - 并提交表单并说表单提交失败。然后我想通过检查每个值是否在旧复选框数组中来反映旧值,如果是,则检查复选框。

我的问题是old('value', 'default') 包含“值”和“默认”,我不能真正使用单独的方法来确定是否应该选中复选框。如果我这样做(如上所述),那么我不能只拥有old('default') - 并在那里进行单独检查 - 因为只有一个参数就可以使其成为old('value')

我不知道在我的情况下如何去做。任何指示或帮助将不胜感激。我希望我能清楚地说明我的情况。

【问题讨论】:

    标签: forms laravel checkbox default


    【解决方案1】:

    你可以试试下面的

    <input type="checkbox" id="card_type1" name="card_type[]" value="easy" 
        @if (in_array('easy', old('card_type', [$parkingLot->m_plots_can_easycard === '1' ? 'easy' : '']))) 
            checked 
        @endif>
    <input type="checkbox" id="card_type2" name="card_type[]" value="icash" 
        @if (in_array('icash', old('card_type', [$parkingLot->m_plots_can_icash20 === '1' ? 'icash' : '']))) 
            checked 
        @endif>
    <input type="checkbox" id="card_type3" name="card_type[]" value="ipass" 
        @if (in_array('ipass', old('card_type', [$parkingLot->m_plots_can_ipass === '1' ? 'ipass' : '']))) 
            checked 
        @endif>
    

    【讨论】:

    • 多么聪明的解决方案。所以基本上你将默认值转换为一个值数组,这样你就可以使用相同的方法来检查数组中的值?
    • @BenKao 是的转换默认值,我们可以使用单个调用in_array。它是否按预期输出了值。
    • 是的,我对其进行了测试,但没有发现问题。请问是否需要像 is_array() 那样检查数组是否为空?
    • 我猜你不需要它,因为默认传递的总是一个数组,card_type 也被定义为一个数组。但是,如果用户弄乱了代码并将输入从card_type[] 更改为card_type,您将需要它。为了解决这个问题,您可以将 old 方法调用包装在 array_wrap 中,例如 array_wrap(old('card_type', [$parkingLot-&gt;m_plots_can_ipass === '1' ? 'ipass' : '']))
    • 好像有问题。当我取消选中所有框并提交表单并使其失败时,复选框将变为默认值。需要注意的几件事:旧的 card_type 数组是空的,默认值不应该再相关了???
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 1970-01-01
    相关资源
    最近更新 更多