Can I do a form to insert data with nested data?

Can I do a form to insert data with nested data?

Table “products”:

  • name
  • prices (reference to table “prices”)

Table “prices”:

  • id
  • currency
  • amount

Is it possible to create a form to add a product, and inside it you can define an unlimited amount of prices? (a product may be have different prices for different currencies)

Something like this:

I believe this could be achieved lets look at this as two parts

Part one is adding the product I see you have an input so all you’d need is to give the input a id and a name like in any form, then in the server action you insert this.

Part two is the the prices and amounts now this is slightly different as you need the form group to be repeating (or however yours is setup needs to repeat)

Once your form group is wrapped in a repeat you get access to the $index which can then be used to create an array when you use the dynamic attribute of name in code view this would look something like

dmx-bind:name="your_array_name[{{$index}}][product_quantity]"

for the quantity then names are up to you to choose and product_quantity can be changed on the price field to create an array for example

dmx-bind:name="your_array_name[{{$index}}][product_price]"

Now looking back at the repeat you will want to create a variable on the page lets say var1 you will use this in the repeats expression var1.value then add more button would on click be var1.value + 1 and the remove button var1.value - 1

Finally in the server connect we now have the array you will select multi insert which gives you a repeat and an insert from here select the array for the repeat expression then the price and quantity should be available for the insert, the id relation comes from the earlier insert in the action so select the identity on that insert

Hope this helps im not sure if there are better ways but this is how I achieved something similar one thing that’s different is the remove will always remove the last item not an item you choose maybe the community has a nice way to solve that.

2 Likes

Anything beyond a simple form, I now tend to use a data store to represent the actual data and then use elements to display and modify that data.

Then I have a hidden form to actually submit data to the server. In that form you have field with its value set to a stringified representation of the data store.

Submit that form and parse the json, then continue as usual.

It eliminates all the index matching etc that can really make your head spin.

So in your case, I could see a data store for all the prices that get wrapped into one json field in the hidden form. Then whatever other fields you need to represent the product.

2 Likes

I would so love to see a tutorial for this. :slight_smile: