Hello. I’m building a dynamic input. It’s crashing when I thought it should be fine. I’m writing it like this:
<%= if @form_stakeholder_option == :new_stakeholder do %>
<.inputs_for
:let={stakeholder}
:if={@form_stakeholder_option == :new_stakeholder}
field={@form[:stakeholder]}
>
<.input field={stakeholder[:company_id]} type="hidden" value={@company_id} />
<.input field={stakeholder[:name]} type="text" label="Name" />
<.input field={stakeholder[:email]} type="email" label="Email" />
</.inputs_for>
<% else %>
<.input
:if={@form_stakeholder_option == :existing_stakeholder}
field={@form[:stakeholder_id]}
type="select"
prompt="Choose a stakeholder"
options={@stakeholders}
/>
<% end %>
On a radio button click, I fire an event, and I replace the form_stakeholder_option
with :existing_stakeholder
. The raised exception is
* (ArgumentError) using inputs_for for association `stakeholder` from `Captain.Schemas.Safe` but it was not loaded. Please preload your associations before using them in inputs_for
Shouldn’t the code that uses inputs_for
don’t render given that I have the conditional if
?
Extra information
My radio buttons are built like this. (I skipped the other radio button)
<input
type="radio"
name="stakeholder_option"
id="new-stakeholder"
value="new_stakeholder"
class="h-4 w-4 border-gray-300 text-zinc-700 focus:ring-0"
phx-update="ignore"
checked={@form_stakeholder_option == :new_stakeholder}
phx-click="change-stakeholder-option"
phx-target={@myself}
/>
<label for="new-stakeholder" class="block text-sm font-medium leading-6 text-gray-900">
New stakeholder
</label>
I’m changing the @form_stakeholder_option
like this:
def handle_event("change-stakeholder-option", %{"value" => value}, socket) do
{:noreply, assign(socket, form_stakeholder_option: String.to_existing_atom(value))}
end
How could I achieve what I want? Depending on the radio button, I either show the stakeholder nested assoc inputs or a select input.