Ash FrameworkAF
Ash Framework7mo ago
7 replies
Jorge Riboldi

"Right" way to do conditional forms

Hello, first of all, thanks for all the work with Ash, it's being incredible and I'm very happy to using it. It's really awesome.

I'm facing a challenge here, and just have some questions if maybe there is a way that AshPhoenix forms can help me here.

I have a very complex form, where several inputs change based on the selection of some attributes.

For example, for this attribute:
attribute :product_category, :atom,
      constraints: [
        one_of: [
          :foo,
          :bar,
          :baz
        ]
      ]

I render this:
<.input
          field={@form[:product_category]}
          type="select"
          label={gettext("Product category")}
          fieldset_class="col-span-8 md:col-span-2"
          options={
            Ash.Resource.Info.attribute(MyApp.SupplyChain.Product :product_category).constraints[:one_of]
          }
        />


But then I have several inputs that render differently if is foo, bar or baz.

And also I actually have other attributes with different conditions too.

My question is, is there a way to do this without manually setting what shows up or not? And also cleaning the form when they change?

Ideally:

selected foo -> foo_field is filled and submitted, bar_field and baz_field are nil

selected foo -> foo_field is filled, but then I change to bar and bar_field is filled and submitted, then foo_field is nil

selected foo -> foo_field is filled, but then I change to bar and bar_field is filled and then returned to foo and submitted, then foo_field is present and bar_field is nil

I thought of using nested forms but multi conditionals not sure if it will work

Right now I could make it work to show or hide fields adding a phx-change to the select, but if I don't "clean" the form it will send data that was hidden

I appreciate any help on this matter.
Solution
I think you'll essentially need to clean up the UI and/or model your input to the action as a union, and use the union form guides.
Was this page helpful?