How to get current url/params in deadview form

I have a toolbar component in my root.html.heex that is a form used to set a couple parameters on the user session when it is submitted to a controller and should redirect the user back to the same page with the same params. The page the user is coming from is a liveview using push_patch to update some filter params. So, the params are changing from what I have access to on conn at the time the toolbar is rendered with root.html.heex. I need to get the current url/params at the time the toolbar component form is submitted and include it as a hidden input in the form params. struggling to figure out how to accomplish this. this component has to be in the root as making it a live_component to handle this and putting it in all the liveviews is probably not going to be possible with the way the app is setup. we do have hotwired/stimulus as a dependency but if possible id like to avoid using it.

You could push an event from the server and handle it in a Phoenix hook. Hooks are pretty much stimulus minus targets and outlets.

Don’t think you can use hooks in dead views

1 Like

I’m under the impression that you want to update the dead part of a live page. Is that incorrect? What’s stopping you for manipulating the dead part dom with regular js from inside a hook?

that is correct. the reason i don’t want to use a hook in the LV to update the dead part is because its not scalable for this application. it would require the hook to be added to all the templates and for anywhere someone wants to use handle_params and push_patch they would also have to know they need to send the event to the client to update the dead part. its too many people and too many templates. i’d like for this to all remain in the dead component dropped into root so it works everywhere and there is only one place that controls it. right now i just have a script tag in the dead view heex that uses JS to add a submit event listener to the form and upon submitting the form adds the path from window.location to a hidden input then submits the form. but, for whatever reason that has a smell to me, so just wanted to see if there was a better way.

So:

  1. The data is only needed when you submit the form
  2. The form exists on a dead part of a live page
  3. The form is backed by a traditional controller

You could intercept the form submission using addEventListener, prevent the default submission, grab and parse the url as needed, ajax the form data to the backend then refresh the page on success

OR

You could use a mutation observer to figure out when the live view content changes, then update the hidden form field

OR

You could capture the refer header on form submit and navigate to there directly from the server.

The “referer” header idea I think is perfect! Going to try going down that route. Thanks!

1 Like