Skip to content

Commit ece9a6f

Browse files
committed
Update guide, add prepare_params
1 parent 8048aae commit ece9a6f

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

documentation/topics/forms-for-relationships-between-existing-records.md

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -159,20 +159,27 @@ Now, let's expose this to a user.
159159
In our view, we create our form as normal.
160160
For update forms, we'll make sure to load our `locations`.
161161

162+
We use the `:prepare_params` option with our `for_update` form to set `"location_ids"` to an empty list if no value is provided.
163+
This allows the user to de-select all `Location`s to update a `Service` so that it's not available at any `Location`.
164+
162165
```elixir
163166
# lib/my_app_web/service_live/form_component.ex
164167
defp assign_form(%{assigns: %{service: service}} = socket) do
165168
form =
166169
if service do
167170
service
168171
|> Ash.load!([:locations, :location_ids])
169-
|> AshPhoenix.Form.for_update(:update, as: "service")
172+
|> AshPhoenix.Form.for_update(:update, as: "service", prepare_params: &prepare_params/2)
170173
else
171174
AshPhoenix.Form.for_create(MyApp.Operations.Service, :create, as: "service")
172175
end
173176

174177
assign(socket, form: to_form(form))
175178
end
179+
180+
defp prepare_params(params, :validate) do
181+
Map.put_new(params, "location_ids", [])
182+
end
176183
```
177184

178185
When rendering the form, we'll have to manually provide the `options` to our `input`.
@@ -195,6 +202,5 @@ Now, when our form is submitted, we will receive a list of location ids.
195202
%{"service" => %{"locations" => ["1", "2"], "name" => "Overhaul"}}
196203
```
197204

198-
199205
That's all we need to do.
200206
We can pass these parameters to `AshPhoenix.Form.submit/2` as normal and `manage_relationship` will create and destroy our `ServiceLocation` records as needed.

0 commit comments

Comments
 (0)