Chrisklein00
Chrisklein00

Reputation: 1

I can't pass parameters to the component Wire Elements Modal

I can't pass parameters to the component.

I have 3 files:

Inside Livewire/test.blade.php ...............

onclick='Livewire.emit("openModal", "test-modal", {{ json_encode(["id_code" => $client->id_code]) }})'>

Inside /Http/Livewire/TestModal.php

namespace App\Http\Livewire;

use LivewireUI\Modal\ModalComponent;
use App\Models\Client;


class TestModal extends ModalComponent
{
    public $id_code;

    public function render($id_code)
    {
        dd($id_code);
        return view('livewire.test-modal');
    }
}

And livewire.test-modal which displays the content of the modal window.

But I can't get the id_code.

Let's see if someone can help me with this. Thanks.

Upvotes: 0

Views: 2844

Answers (2)

Daxy_
Daxy_

Reputation: 11

So I had the same issue pretty much. I solved it by adding the $id_code to the mount method. I hope it helps

namespace App\Http\Livewire;

use LivewireUI\Modal\ModalComponent;
use App\Models\Client;

class TestModal extends ModalComponent
{
    public $id_code;

    public function mount($id_code){
        $this->id_code = $id_code
    }



    public function render()
    {
        $elCliente = Client::where("erp_code", $this->id_code)->first();
        dd($elCliente);
        return view('livewire.test-modal');
    }

}

Upvotes: 1

Qirel
Qirel

Reputation: 26460

Livewire.emit("openModal") will emit an event that you can listen to in your components. The render() method in Livewire does not accept a parameter, so instead you need to listen to that event, and do your actions in a separate method instead.

By adding

protected $listeners = ['openModal' => 'openModal'];

the component will now listen to the event openModal (key in the array) being dispatched, and then fire the method openModal() (value in the array). Since you pass in two parameters, "test-modal" and a JSON parameter, you can accept those in that method.

namespace App\Http\Livewire;

use LivewireUI\Modal\ModalComponent;
use App\Models\Client;

class TestModal extends ModalComponent
{
    public $id_code;

    protected $listeners = ['openModal' => 'openModal'];

    public function openModal($name, $data)
    {
        $this->id_code = $data['id_code'];
    }

    public function render()
    {
        return view('livewire.test-modal');
    }
}

Upvotes: 0

Related Questions