nheingit

nheingit

How To Set Up Default Values For Embeded Resources in forms?

Hello, I set up an ash resource that has some embedded resources.

(As a side note, I’d love some array helpers for the ash_forms, as I didn’t really want to create embedded resources in the first place, it could have just been an {:array, :string} but I didn’t see a clean way to map that to the helpers that exist currently! If you agree I’d love to help out with a PR on that)

But I’m trying to render some default values in the forms, and I don’t quite understand how to do that. My form looks like this currently.

      AshPhoenix.Form.for_create(RunConfigData, :create,
        api: Smol.Pipelines,
        actor: socket.assigns.current_user,
        forms: [
          models: [
            type: :list,
            resource: Model,
            data: [
              %{
                "model" => "gpt-4o"
              },
              %{
                "model" => "claude-3-opus-20240229"
              }
            ],
            create_action: :create,
            update_action: :update
          ],
          messages: [
            type: :list,
            resource: Message,
            data: [
              %{
                "message" => "msg1"
              },
              %{
                "message" => "msg2"
              }
            ],
            create_action: :create,
            update_action: :update
          ]
        ]
      )
      |> to_form()

And when I render the forms with the inputs_for:

            <.inputs_for :let={model_form} field={@run_config_form[:models]}>
              <div class="flex space-x-2 mt-1">
                <.input
                  type="text"
                  field={model_form[:model]}
                  phx-debounce="blur"
                  class="block w-full shadow-sm sm:text-sm border-gray-300 rounded-md"
                />
              </div>
            </.inputs_for>

It works in the sense that it will render two inputs, so it’s being picked up and that’s great, but I’d like those default value I set in the liveview to populate the value of the input when the page is first loaded.

So the question is, in this situation how do I access the value of the object in the inputs_for loop?

I do it with the other values in my form that aren’t embedded resources in the actual action of the resource like this:

defmodule Smol.Pipelines.RunConfigData do
  alias Smol.Pipelines.{Model, Message}

  use Ash.Resource,
    # Use in-memory storage since it doesn't need to persist
    data_layer: Ash.DataLayer.Ets

  attributes do
    uuid_primary_key :id
    attribute :repository_location_name, :string, allow_nil?: false
    attribute :job_name, :string, allow_nil?: false

    attribute :data_fetch_end_time, :utc_datetime, allow_nil?: false
    attribute :data_fetch_duration_hours, :integer, allow_nil?: false
    attribute :list_id, :integer, allow_nil?: false

    attribute :models, {:array, Model}, allow_nil?: false
    attribute :messages, {:array, Message}, allow_nil?: false
    attribute :system_prompt, :string, allow_nil?: false
    attribute :overrides, :map, allow_nil?: true
  end

  actions do
    defaults [:update]

    create :create do
      change fn changeset, _ ->
        changeset
        |> maybe_set_default(:repository_location_name, "data_ingestion")
        |> maybe_set_default(:job_name, "data_summary_job")
        |> maybe_set_default(:list_id, 1_585_430_245_762_441_216)
        |> maybe_set_default(:system_prompt, "Put your system prompt here")
        |> maybe_set_default(:data_fetch_duration_hours, 24)
        |> maybe_set_default(:overrides, nil)
      end
    end
  end

  defp maybe_set_default(changeset, field, default_value) do
    if Ash.Changeset.get_attribute(changeset, field) == nil do
      Ash.Changeset.change_attribute(changeset, field, default_value)
    else
      changeset
    end
  end
end

But I don’t quite understand how I would do that in the embedded resources.

Sorry if all of this isn’t quite clean, I’m quite new to Ash and am still getting my footing on how to do things, so please let me know if I’m doing something weird!

Marked As Solved

zachdaniel

zachdaniel

Creator of Ash
  1. Would definitely love some array helpers for ash_phoenix. we have a built in embed called WrappedValue and if you call inputs_for on a value that is a list we can render a form per item in WrappedValue forms. May need to do some work internally to clean up the paramification of them automatically though, would need to double check

  2. Setting the default values for embedded forms in the action would be pretty tough, NGL. You’d be best off doing it in the the LiveView probably, like setting some params in a preflight call to validate or something along those lines. I’d have to think harder on it, but my suggestion is that this kind of defaulting is more about the UI layer than the model itself, and so it should probably go in the LiveView.

Where Next?

Popular in Questions Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New

Other popular topics Top

minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New

We're in Beta

About us Mission Statement