Skip to content

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

Open
@signalblue

Description

@signalblue

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions