petelacey
LiveView: How to access ID of a nested resource's parent
I’m new to Elixir/Phoenix. Please forgive me if this is obvious or has been asked before, I’ve looked but cannot find an answer to what is probably a simple question.
In Phoenix, I have an ordinary nested resource: accounts have many users. I want to use LiveView to allow an admin to add one user after another. In my router I have:
resources "/accounts", AccountController do
live "/users", UserLive.New
end
When an admin visits e.g. /accounts/99/users, I want to show account information, any existing users, and some fields to enter a new user.
My question is how do I access the account_id (99) that would normally be in the params? Also, I assume I want to retrieve the account and existing users in the mount function, is that correct? Something like this:
def mount(session, socket) do
account = Accounts.get_account!(?????)
{:ok, assign(socket, changeset: changeset, account: account)}
end
Thank you in advance.
Pete
Marked As Solved
LOG67
I am also new to Elixir/Phoenix. I can see 2 ways to accomplish this:
In your router instead of the live, you can use a regular get with a controller and action and then render the LiveView from the controller’s action. In the action you have access to params so you can set the session for the LiveView then in the LiveView module’s mount you can extract the session value.
or
You can implement the handle_params(params, url, socket) function in your LiveView and extract the account_id from params. Keep in mind that handle_params will be invoked every time there is a live redirect on the page and at the first request and also when the socket is connected (the same way mount will be invoked on the initial request and upon socket connection).
Also Liked
preciz
I haven’t used it yet but sounds like you are looking for this:
Edit:
I might be wrong. Make sure to look into this one also:







