Čamo
Čamo

Reputation: 4172

Edit form issue with default value for checkbox regarding old value on error

I have a problem that seems like a bug with the Laravel checkbox old() value. I have a code where I want to fill default values on edit and, if the form submit fails, I want to fill old() value to the form.

The problem is when the original database value is TRUE and the new form submit is false for the checkbox. Laravel old() does not catch the FALSE value on submit for checkbox and fills the original value which is TRUE.

<input name="active" type="checkbox"
    @if( old('active', $voucher->active ?? false) ) checked='checked' @endif
>

It falls back to the default value if submit is FALSE. All solutions I found are wrong. How can I solve it?

Upvotes: 0

Views: 1926

Answers (3)

Levi
Levi

Reputation: 69

Try this

<input type="checkbox" class="custom-control-input" name="active" value="1"
    @if((old('_token') && old('active') != null) || (old('_token') == null && $voucher->active))
    checked 
    @endif
>

Upvotes: 1

Čamo
Čamo

Reputation: 4172

So the solution would be to test another field like @old('submit')

<input name="active" type="checkbox"
    @if( old('active') || (!old('submit') && $voucher->active) ) checked='checked' @endif
>

which is send by submit. It seems it works but dont know if it is always send or if there is a use case where submit could be empty.

Upvotes: 0

John Lobo
John Lobo

Reputation: 15319

I think it should be

<input name="active" type="checkbox"  value="{{old('active', $voucher->active ?? 0)}}" {{isset($voucher->active)?'checked':''}}>

still want to check if its true or not or 1 or 0 you can check like below

<input name="active" type="checkbox" value="{{old('active', $voucher->active ?? 0)}}" {{(isset($voucher->active)&&$voucher->active==true)?'checked':''}}>

As per me.for your requirement checkbox is not suitable one .Better you have to go for radio button .So user can choose true or false on active

Upvotes: 1

Related Questions