鍍金池/ 問(wèn)答/PHP/ laravel 表單驗(yàn)證錯(cuò)誤時(shí)怎么保留用戶選中的radio或checkbox

laravel 表單驗(yàn)證錯(cuò)誤時(shí)怎么保留用戶選中的radio或checkbox

當(dāng)用戶提交表單時(shí),表單中含有radio或checkbox,如果是input或textarea還好可以通過(guò)old()函數(shù)獲取存儲(chǔ)在session中的值,但是如果是radio或checkbox要怎樣通過(guò)對(duì)比old()里面的值進(jìn)行選中呢?

詳見(jiàn)下圖:

laravel 表單驗(yàn)證錯(cuò)誤時(shí)怎么保留用戶選中的radio或checkbox

代碼片段:

<div class="form-group row mb-4">
    <label for="staticPhone" class="col-md-2 col-form-label">手機(jī)</label>
    <div class="col-md-10">
        <input type="text" name="phone" class="form-control" id="staticPhone" value="{{ old('phone') ? old('phone') : $user->phone }}" placeholder="手機(jī)">
        <small class="form-text text-muted">[可選] 輸入用戶手機(jī)號(hào)碼</small>
    </div>
</div>

<div class="form-group row mb-4">
    <label class="col-md-2 col-form-label">性別</label>
    <div class="col-md-10">
        <div class="custom-control custom-radio custom-control-inline">
            <input type="radio" class="custom-control-input" id="staticBoy" name="gender" value="1" checked required>
            <label class="custom-control-label" for="staticBoy">男</label>
        </div>
        <div class="custom-control custom-radio custom-control-inline">
            <input type="radio" class="custom-control-input" id="staticGirl" name="gender" value="0" required>
            <label class="custom-control-label" for="staticGirl">女</label>
        </div>
        <small class="form-text text-muted">[必選] 選擇用戶性別</small>
    </div>
</div>

當(dāng)old不存在值時(shí)需要和$user->gender中的值進(jìn)行對(duì)比選中!
求解。

回答
編輯回答
風(fēng)清揚(yáng)
<div class="form-group row mb-4">
    <label for="staticPhone" class="col-md-2 col-form-label">手機(jī)</label>
    <div class="col-md-10">
        <input type="text" name="phone" class="form-control" id="staticPhone" value="{{ old('phone') ? old('phone') : $user->phone }}" placeholder="手機(jī)">
        <small class="form-text text-muted">[可選] 輸入用戶手機(jī)號(hào)碼</small>
    </div>
</div>

<div class="form-group row mb-4">
    <label class="col-md-2 col-form-label">性別</label>
    <div class="col-md-10">
        <div class="custom-control custom-radio custom-control-inline">
            <input type="radio" class="custom-control-input" id="staticBoy" name="gender" value="1" required {{ old('gender') != ''?(old('gender')=='1'?'checked':''):($user->gender == '1'?'checked':'') }}>
            <label class="custom-control-label" for="staticBoy">男</label>
        </div>
        <div class="custom-control custom-radio custom-control-inline">
            <input type="radio" class="custom-control-input" id="staticGirl" name="gender" value="0" required {{ old('gender') != ''?(old('gender')=='0'?'checked':''):($user->gender == '0'?'checked':'')  }}>
            <label class="custom-control-label" for="staticGirl">女</label>
        </div>
        <small class="form-text text-muted">[必選] 選擇用戶性別</small>
    </div>
</div>
2018年3月24日 23:59