根据数据库记录或以前的编辑状态将复选框的状态设置为“检查”?

时间:2021-02-02 10:00:40

标签: php laravel

我正在为此苦苦挣扎,而 Google 却让我失望了!

在下面的代码中,一切正常。但如果表单上的其他验证规则失败,我希望记住这些复选框的更改状态。

在表单的其他部分,我可以使用 'old' 变量来检索以前的输入。

{{ old('Bathrooms', optional($prop ?? null)->a_baths) }}

我认为我遇到的问题是因为请求中的 'tags' 属性是一个数组,那么它也是 Old 变量中的一个数组吗?我需要以某种方式结合这两个检查..

<div class="form-row row mt-1">
<label class="col-md-3 col-form-label text-md-right" for="tags">Features:</label>
<div class="col-sm-6">
    @php $currentTags = $prop->tags->pluck('id'); @endphp   

    @foreach($tags as $tag)
    <div class="custom-control custom-switch">
        <input type="checkbox" class="custom-control-input" 
            name="tags[{{ $tag->id }}]"
            value="{{ $tag->id }}" 
                @if(in_array($tag->id, $currentTags->toArray())) checked @endif
            id="tags[{{ $tag->id }}]">
        <label class="custom-control-label" for="tags[{{ $tag->id }}]">{{ $tag->name }}</label>
    </div>
    @endforeach 
    @error('tags') 
    <p class="font-weight-light text-danger">{{ $message }}</p>
    @enderror
</div>

1 个答案:

答案 0 :(得分:0)

以下更改应该适合您:

改变

@php $currentTags = $prop->tags->pluck('id'); @endphp 

@php $currentTags = old('tags', $prop->tags->pluck('id')->toArray()); @endphp 

if(in_array($tag->id, $currentTags->toArray())) checked @endif

@if(in_array($tag->id, $currentTags)) checked @endif

您可以使用 old() 助手将 $currenTags 设置为默认情况下 $prop 的选定标签以及提交表单时的选定标签。

完成的代码:

<div class="form-row row mt-1">
    <label class="col-md-3 col-form-label text-md-right" for="tags">Features:</label>
    <div class="col-sm-6">
        @php $currentTags = old('tags', $prop->tags->pluck('id')->toArray()); @endphp

        @foreach($tags as $tag)
            <div class="custom-control custom-switch">
                <input type="checkbox" class="custom-control-input"
                       name="tags[{{ $tag->id }}]"
                       value="{{ $tag->id }}"
                       @if(in_array($tag->id, $currentTags)) checked @endif
                       id="tags[{{ $tag->id }}]">
                <label class="custom-control-label" for="tags[{{ $tag->id }}]">{{ $tag->name }}</label>
            </div>
        @endforeach
        @error('tags')
            <p class="font-weight-light text-danger">{{ $message }}</p>
        @enderror
    </div>
</div>
相关问题