lundi 23 novembre 2020

Laravel - Is there any better approach to check the checkbox with the user previous input value in blade?

I have a checkbox

<input type="checkbox" name="example">

The user submits the form and return back due to failed validation so I want to show the previous state of the checkbox

<input
    type="checkbox"
    name="example"
    {!! old('example') ? 'value="1" checked' : 'value="0"' !!}>

First question here is that, what to do with validation now? if it was 0 or 1 I would add boolean validation but now the first time it is on and after that it is 0 or 1.

Someone may say if you use that {!! old('example') ? 'value="1" checked' : 'value="0"' !!} initially, its value won't be on anymore.

So my first question changes to this: Initially the value of old('example') is null so the checkbox doesn't have checked attribute and the value of checkbox would be 0. Now when the user submits the form the old('example') has value (IT IS NOT NULL) and so this time the the checkbox has checked attribute and its value is 1 while it mustn't.

========

Another issue I encounter with is that, if old('example') has true value (which means the user had checked the checkbox), I should put something to check the checkbox. But it is not finished yet. I want to check the value of example that is in database so if the old('example') has false value(which means the user hadn't checked the checkbox) I want to check the value of example, if its value is 1 to check the checkbox and set the value of checkbox to 1 else 0. So what comes to my mind is this:

<input
    type="checkbox"
    name="example"
    value="{!! old('example', isset($collection) ? $collection->example : null) == '1' : '1' : '0' !!}">

Now the problem is that old('example') would be on or NOTHING. And the value of $collection->example would be 1 or 0 or null. So if I compare it with '1' it won't be true even if the old('example') is true and similarly if I compare it with on, it won't be true even if the value of $collection->example is true. So let's do this:

@if(old('example') == 'on' || (isset($collection) && $collection->example))
    <input type="checkbox" name="example" value="on" checked="checked">
@else
    <input type="checkbox" name="example">
@endif

by this code above the issue is fixed. But is there any other better approach?

So my question is what to do with the validation in the back-end and of course what to do with check-boxes in front-end in an better approach without getting involved in jQuery and such a like?




Aucun commentaire:

Enregistrer un commentaire