Passing the Organization id to the Link schema

@dhony I think I got a good grasp on your problem. Here’s my take on how to solve this while still making code simple.

First of all, there’s two routes for links: :new and :create.

They look roughly like this:

get /orgs/:organization_id/new, YourController, :new
post /orgs/:organization_id, YourController, :create

Your org page should link to :new, where the form lives. The :create route doesn’t have any HTML, its just a “do things and redirect” kind of route.

Your :new route could look roughly like this:

def new(conn, %{"organization_id" => organization_id) do
  changeset = YourContext.link_changeset(%{organization_id: organization_id})
  # assign to conn and render here

And here’s the magic:

<.inputs_for :let={f} field={@whatever_assign}>
  <.input type="hidden" field={f[:organization_id]} />
  ... your inputs here

The hidden input will just work on this case.

Depending on your phoenix version the HTML will be different, in that case could you paste your form here?

1 Like

My Phoenix version is 1.7.6.

Here is my link_form.html.heex with the newly created input hidden organization_id field (the magic trick :sweat_smile:):

<.simple_form :let={f} for={@changeset} action={@action}>
  <.error :if={@changeset.action}>
    Oops, something went wrong! Please check the errors below.
  <.input field={f[:url]} type="text" label="Url" />
  <.input field={f[:visits]} type="number" label="Visits" />
  <.input field={f[:organization_id]} type="hidden" /> # <- the org_id hidden field
    <.button>Save Link</.button>

I’m adapting my original Link new function to comporting your instructions.

def new(conn, %{"organization_id" => organization_id}) do
    changeset = Links.change_link(%Link{}, %{organization_id: organization_id})
    render(conn, :new, changeset: changeset)

And now the organization_id is being stored on links table as expected.

As always, thanks for your help @lubien :raised_hands:

1 Like