I have a very simple Livewire component with a text field and a date picker:
<!-- test.blade.php -->
<div>
<input type="text" wire:model="test" placeholder="Test">
<input datepicker="" wire:model="start" datepicker-format="dd.mm.yyyy" type="text" placeholder="Datum ...">
</div>
/* Test.php */
class Test extends Component
{
public $test;
public $start;
public function mount()
{
$this->start = now()->format('d.m.Y');
}
public function render()
{
return view('livewire.test');
}
}
The date picker I use is the Flowbite Datepicker.
When I change the date and then change the test input field, the date picker resets to today date.
What do I need to to to keep the value of start?
What I have already tried? I tried the wire:ignore on the date picker, but this does not help.
CodePudding user response:
I made some debugging on this, found in the datepicker code we can use "changeDate" event on the input to connect it to Livewire. Wonder why it is not documented at all. Here is the code:
The component view:
<div>
<input type="text" wire:model="test" placeholder="Test">
<input name="start" id="startInput" inline-datepicker="" wire:model="start" datepicker-format="dd.mm.yyyy" type="text" placeholder="{{$start}}" value="{{$start}}" datepicker-autohide>
<br>
<br>
Actual proprties now:
<hr>
<div>
{{$test}} <br>
{{$start}}
</div>
</div>
The component:
namespace App\Http\Livewire;
use Livewire\Component;
class SomeComponent extends Component
{
public $test;
public $start;
protected $listeners = ['changeDate' => 'changeDate'];
public function changeDate($date)
{
$this->start = $date;
}
public function mount()
{
$this->start = now()->format('d.m.Y');
}
public function render()
{
return view('livewire.some-component');
}
}
And the html where the livewire component is being included, together with the js that listens for the Flowbite Datepicker event, and launches the livewire event after that.
<body>
<div>
<br>
<br>
@livewire('some-component')
</div>
<script>
document.getElementById("startInput").addEventListener("changeDate", function (e) {
Livewire.emit('changeDate', e.detail.datepicker.inputField.value)
});
</script>
@livewireScripts
</body>
Works as expected on my side. Cheers