Home  >  Q&A  >  body text

"Date picker reset on Livewire update"

<p>I have a very simple Livewire component that contains a text field and a date picker: </p> <pre class="brush:html;toolbar:false;"><!-- 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="Date ..."> </div> </pre> <pre class="brush:php;toolbar:false;">/* 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'); } } </pre> <p>The date picker I use is Flowbite Datepicker. </p> <p>When I change the date and then change the test input field, the date picker resets to today's date. </p> <p>What do I need to do to maintain the value of start? </p> <p><strong>What have I already tried? </strong> I tried using wire:ignore on the date picker but that didn't help. </p>
P粉696146205P粉696146205393 days ago470

reply all(1)I'll reply

  • P粉807471604

    P粉8074716042023-08-26 14:38:51

    I did some debugging here and found that in the code of the date picker, we can use the "changeDate" event to connect it with Livewire. Not sure why this wasn't documented. The following is the code:

    Component view:

    <div>
    <input type="text" wire:model="test" placeholder="测试">
    <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>
    当前属性:
    <hr>
    <div>
        {{$test}} <br>
        {{$start}}
    </div>
    </div>

    Components:

    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 code that contains the Livewire component, and the js code that listens to the Flowbite date picker event and triggers 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 in my environment. cheers

    reply
    0
  • Cancelreply