Extracting params from a form with deeply nested arrays of values

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 06:07:21

问题


Let's say that I have a form that is used for adding a new product. Each product may have multiple sizes where each size, in its turn, may have multiple options. The form would look something like that:

<form accept-charset="UTF-8" action="/products?_format=json" method="post">

  <input id="product_name" name="product[name]" type="text">

  <input id="product_product_sizes_name" name="product[product_sizes][][name]" type="text">

  <input id="product_product_sizes_product_size_options_name" name="product[product_sizes][][product_size_options][][name]" type="text">
  <input id="product_product_sizes_product_size_options_size" name="product[product_sizes][][product_size_options][][size]" type="text">

  <input id="product_product_materials_name" name="product[product_materials][][name]" type="text">

  <button type="submit"> Create </button>

</form>

My purpose here is to receive a nested map in the controller in order to handle the data and I would expect to receive a map like this:

%{
  "product" => 
    %{
      "name" => "value", 
      "product_materials" => [
        %{
          "name" => "value"
        }
      ], 
      "product_sizes" => [
        %{
          "name" => "value",
          "product_size_options" => [
            %{
              "name" => "value",
              "size" => "value"
            }
          ]
        }
      ]
    }
}

but instead what I get is this:

%{
  "product" => 
    %{
      "name" => "value", 
      "product_materials" => [
        %{
          "name" => ""}
      ], 
      "product_sizes" => [
        %{
          "name" => ""
        }, 
        %{
          "product_size_options" => [
            %{
              "name" => ""
            }
          ]
        }, 
        %{
          "product_size_options" => [
            %{
              "size" => ""
            }
          ]
        }
      ]
    }
}

So I am wondering if I am doing something wrong here and it is actually possible to change the form names and receive the map that I expect or this is not the case and I should use explicit indexes (as in [0], [1] and so on instead of []) or something of the kind and manually merge the data after submission?

来源:https://stackoverflow.com/questions/47628425/extracting-params-from-a-form-with-deeply-nested-arrays-of-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!