How to add additional formats to a controller?

I’ve updated my app to the current Phoenix 1.7.0-rc.0. My controller is erroring when it’s called with a format other than JSON or HTML:

(RuntimeError) no view was found for the format: ics. The supported formats are: ["html", "json"]

I changed a def call("show.ics", ... in a trip_view.ex file to a new trip_ics.ex file in my controllers path.

In my config/config.exs I have a mime type:

config :mime, :types, %{
  "text/calendar" => ["ics"]
}

I have a pipeline configuring this route:

  pipeline :icalendar do
    plug(:accepts, ["ics"])
    plug(TrailingFormatPlug)
  end

In my trip_controller.ex, I even know that the right format is being passed in:

  def show(conn, %{"id" => id}) do
    case get_format(conn) do
      "ics" ->
          ...
         render(conn, :show, trip: trip)

      other ->
        ...
    end
  end

What else do I need to do to get Phoenix to recognize the ics format? I can force it in my controller by adding plug :put_view, ics: IdoWeb.TripICS, but that’s obviously fighting against it.

Thanks!

What are the options you pass to use Phoenix.Controller?

2 Likes

Aaah, that was it. I didn’t realize the formats were specified in the AppWeb.ex module. This did the trick:

  def controller do
    quote do
      use Phoenix.Controller,
        namespace: IdoWeb,
        formats: [:html, :json, :ics],
        layouts: [html: IdoWeb.Layouts]

      import Plug.Conn
      import IdoWeb.Gettext

      unquote(verified_routes())
    end
  end

Thanks!

1 Like