13
votes

I have a phoenix route that I want to POST some form data to, however there are about 4 fields of the form that are optional (the form is constructed by the end user and therefore these fields may not exist in the POST payload)

In the Phoenix controller for the route, how would you handle this?

For example:

My form has

Field1,
Field2
Field3 (optional)
Field4 (optional)
Field5 (optional)

And POSTing the form must always have Field1 and Field2 but can have any combination of the other fields.

so my controller code so far is like this:

def create(conn, %{"field1" => field1, "field2" => field2) do
end

How do I make the other 3 optional? If I add them all in then they will be required and I don't want to have to make a function for each of the potential submitted forms as it seems overkill.

1

1 Answers

29
votes

The parameters received by the controller are just a map, so you're probably looking for something like Map.get/3. With this function, you can do something on these lines:

def create(conn, %{"field1" => f1, "field2" => f2} = params) do
  f3 = Map.get(params, "field3", "my default value")
  # similar for the other fields
end

You could also create a map that contains all the default values for the optional parameters and then use Map.merge/2:

@optional_params %{"field3" => "default3", "field4" => "default4"}

def create(conn, %{"field1" => f1, "field2" => f2} = params) do
  # `params` has precedence over `@optional_params`, that's why we're using it
  # as the second argument here.
  params = Map.merge(@optional_params, params)
end