Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inconsistent option loading with Backpex.Fields.HasMany and Backpex.Fields.BelongsTo #940

Open
signalblue opened this issue Mar 9, 2025 · 0 comments

Comments

@signalblue
Copy link

Describe the bug
(I could be doing this a completely wrong way, but for now this is what I've come up with)

I have 3 associations in a live resource: parent association A (BelongsTo) that depends on another association B (BelongsTo) and finally a list of items C (HasMany).

In B's options_query I do

options_query: fn query, assigns ->
      parent_id = assigns[:form].params["parent_id"] || assigns[:item]. parent_id

      if parent_id do
        query
        |> where([q], q.parent_id == ^parent_id)
      else
        query |> where([q], false)
      end
    end

and that works. As I change the options for A, the list of options for B changes. This is because BelongsTo updates the options in render_form and I have access to the form's parent_id update.

On HasMany on the other hand, the exact same logical code doesn't work correctly:

options_query: fn query, assigns ->
      second_id = assigns[:form].params["second_id"] || assigns[:item]. second_id

      if second_id do
        query
        |> where([q], q.second_id == ^second_id)
      else
        query |> where([q], false)
      end
    end

I looked into the code and I think it's because BelongsTo updates the options only in before_changeset which doesn't get the form updates. second_id doesn't reflect the new selection so the options aren't correct, and they don't update in render_form.

Would a fix be to also update the options in render_form ? If so I'm happy to make the change in a PR, but am not sure if I'm missing anything else. Thank you!

Expected behavior
There should be some consistency with BelongsTo and HasMany on how and when their options get updated based on form and changeset changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant