I'm trying to use the Bootstrap toggle switch in a form, but on submit, the switch toggle doesn't show the right state of the toggle. e.g. if it is checked on page load and the user changes it to unchecked, on submit it is still checked:
(I added the wire:ignore because otherwise, the switch displays as a normal checkbox, maybe that's the problem)
<div class="form-group" wire:ignore>
<label>Active</label>
<input type="checkbox" name="active" value="1" class="switch" wire:model.lazy="active">
</div>
<div class="form-group" wire:ignore>
<label>In Stock</label>
<input type="checkbox" name="in_stock" value="1" class="switch" wire:model.lazy="inStock">
</div>
JS:
$(".switch").bootstrapSwitch({
onText: 'Yes',
offText: 'No',
size: 'mini'
});
In the Livewire component:
public function mount(Coffee $coffee)
{
$this->coffee = $coffee;
if(!is_null($this->coffee->id)) {//update
$this->name = $this->coffee->name;
$this->active = $this->coffee->active;
$this->inStock = $this->coffee->in_stock;
} else {//create
//Default values for create
$this->active = 1;
}
}
public function storeCoffee()
{
$this->validate();
$slug = str_slug($this->name, "-");
$active = //What to put here?
$inStock = //What to put here?
$coffee = [
'name' => $this->name,
'active' => $active,
'in_stock' => $inStock,
];
if(is_null($this->coffee->id)) {//create
Coffee::create($coffee);
alert()->success('Congrats!', 'You created a coffee');
} else { //update
Coffee::find($this->coffee->id)->update($coffee);
alert()->success('Congrats!', 'You updated the coffee');
}
return Redirect::route('coffees.index');
}
I saw lots of tutorials of how to make a component for the toggle switch like this one:
https://codelapan.com/post/how-to-update-data-status-with-toggle-switch-in-laravel-livewire#mcetoc_1fjadvs5824
But I don't want the toggle to update the database as the user changes it, I want it to update the database only when the form is submitted together with all the rest of the fields in the form.
So if the user switched it on or off, but did not submit the form it should not update the database.
Can anyone help on how to do that please?