live_select
live_select copied to clipboard
Option update callback
Define a callback to send updated options to the LiveView or Component where LiveSelect component is initialized.
Hi! What is the use-case for this change? When an option is selected/removed, a change event is triggered on the form, right?
Hi, @maxmarcon!
Yes, when an option is selected / removed, an event is triggered to the form.
To get notified of any option selected / removed, we need pass on_option_update attribute and handle its update event in the form.
When initializing live_select from a LiveView, we can use:
<.live_select
field={@form[:city_search]}
on_option_update={fn option -> send(self, option) end}
/>
and to handle its event:
def handle_info(%{option_click: option}, socket) do
...
{:noreply, socket}
end
def handle_info(%{option_remove: option}, socket) do
...
{:noreply, socket}
end
If initializing it inside another component, one may write:
<.live_select
field={@form[:city_search]}
phx-target={@myself}
on_option_update={fn option -> send_update(@myself, option) end}
/>
and to handle its event:
def update(%{option_click: option}, socket) do
...
{:ok, socket}
end
def update(%{option_remove: option}, socket) do
...
{:ok, socket}
end
This can be useful in cases when someone wants to do certain actions while the user is selecting options, or to track user activity.
Hi sorry my comment wasn't clear: you're already getting a change event in the form when the user selects/deselects an option. I don't see the need for passing a callback to get the same information.