Set_attribute makes input field empty when updating resource

I have a resource that has a field that can be nil:

attribute :cma_url, :string

Now I want to have a create and a update action that will need this field to not be nil.

To achieve that, I did this:

create :create do
  argument :cma_url, :string, allow_nil?: false

  change set_attribute(:cma_url, arg(:cma_url))
end

update :update do
  argument :cma_url, :string, allow_nil?: false

  change set_attribute(:cma_url, arg(:cma_url))
end

This works great for my create action, when I use it in AshPhoenix.Form.for_create.

The problem is with the update action, when I use it with AshPhoenix.Form.for_update, the cma_url input field will be empty even if that fields has already some value to it.

If I replace it with:

update :update do
  accept [:cma_url]
end

Now it works, but now the cma_url field will not be required anymore in the form.

How can I fix that?

The easiest way is instead of adding an attribute to use require_attributes [:cma_url] in your action. That allows you to express that an attribute is required even if it typically is not.

Alternatively, you could use a validation in the action

validate present(:cma_url) # <- put this in the action you want to require it on
2 Likes

Damn! I was not aware of require_attributes, amazing as always!