slouchpie

slouchpie

Using Phoenix forms with Absinthe @graphql attribute in controller

I have finished reading Craft GraphQL APIs in Elixir with Absinthe (Pragprog) and I am trying to expand upon the item_controller.ex to allow for “menu item” editing.

I have made these functions in the controller:

  @graphql """
  query ($id: ID!) {
  menu_item(id: $id) @put {
  name
  description
  }
  }
  """
  def edit(conn, %{data: %{menu_item: item}}) do
    render(conn, "edit.html", item: item)
  end

  @graphql """
  mutation UpdateMenuItem($id: ID!, $input: MenuItemInput!) {
    updatedMenuItem: updateMenuItem(id: $id, input: $input) {
      errors { key message }
      menuItem {
        name
        description
        price
      }
    }
  }
  """
  def update(conn, %{data: %{menu_item: _}}) do
    conn
    |> redirect(to: "/admin/items")
  end
  def update(conn, %{errors: errors}) do
    conn
    |> put_flash(:info, Enum.reduce(errors, "", fn e, a -> a <> e.message end))
    |> redirect(to: "/admin/items")
  end

Here is my edit.html.eex:

<%= render "form.html",
Map.put(assigns, :action,
Routes.item_path(@conn, :update, @item)) %>

Here is my form.html.eex:

<%= form_for @conn, @action, [method: :put, as: :input], fn f -> %>
    <div class="form-group">
        <label for="description">Description</label>
        <input type="string" id="description" as="description" name="description" value="<%= @item.description %>"/>
        <label for="price">price</label>
        <input type="string" id="price" name="price" value="<%= @item.price %>"/>
        <label for="name">name</label>
        <input type="string" id="name" name="name" value="<%= @item.name %>"/>
        <label for="category">category</label>
        <input type="string" id="category" name="categoryId" value="<%= @item.category_id %>"/>
    </div>
    <%= submit "Update", class: "btn btn-primary" %>
<% end %>

But I get an error when I submit the form. This is the error:

In argument "input": Expected type "MenuItemInput!", found null.
Variable "input": Expected non-null, found null.

It makes sense to me. I could, for example change the name attribute of any of the input elements in form.html.eex to be "input" and then I would get a different error:

Argument "input" has invalid value $input.

Again, it makes sense to me. The $input argument is not a MenuItemInput variable.

So I am looking to approach this in either of 2 possible ways:

  1. In the form.html.eex, I create a “form within a form” so that it has an “input” field which, in turn, has several fields.

  2. In the item_controller I pass variables into the @graphql module attribute. I simply don’t know how to do this. I experimented with a lot of strange syntax because I cannot even find examples of SDL that have the variables inline.

Any advice/criticism/ideas are very welcome. I’m sure somebody else has done this since it seems like a natural thing to try after finishing the book.

Marked As Solved

slouchpie

slouchpie

I answered my own question! I just had to change my @graphql query to this:

  mutation UpdateMenuItem($id: ID!, $description: String!, $name: String!, $price: Decimal!, $categoryId: ID!) {
    update_menu_item(id: $id, input: {description: $description, name: $name, price: $price, categoryId: $categoryId}) {
      errors { key message }
      menu_item {
        name
        description
        price
      }
    }
  }

So it seems you cannot really use custom input types like MenuItemInput when using this @graphql module attribute in Phoenix controllers. Also I had to use snake-case for the field names.

P.S. I changed my controller update function signature to this:

def update(conn, %{data: %{update_menu_item: %{errors: nil, menu_item: menu_item}}}) do

Also Liked

slouchpie

slouchpie

Still talking to myself 1 month later…
I tried writing a test to recreate the problem:
https://github.com/peaceful-james/absinthe_phoenix/blob/6a4ff3c7aa132acdc85a4933eda805a5ebefce2b/test/absinthe/phoenix/controller_test.exs#L163

I hope this might help any of the core Absinthe team looking into this.

Where Next?

Popular in Questions Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New

Other popular topics Top

Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement