How Can I Pass an Array to a Server Action to Write to the Database?

Perquisites:

  • App Connect Data Store component added, ID has been set to: responses
  • Set the Data Store Schema, added 1 variable called: attendee_id
  • For the purposes of the demo, I have setup a flow to insert two records to the data store on page load, my code for this is: (This will be replaced with your own method for your app)
<body is="dmx-app" id="test" dmx-on:load="run([{run:{action:`responses.insert({attendee_id: 2})`}},{run:{action:`responses.insert({attendee_id: 3})`}}])">

Form

A form needs to be created on the page, set to post and set to your server action file. Within the form, create a Form Row and make it a repeat. Set the repeat expression to your datastore component, in this case it’s called responses.data.

Within this form row repeat, there needs to be a text input. The ID of this input is called attendee_id (to match the datastore variable for my reference) and needs a dynamic value set to the datastore variable attendee_id.

Switch to code view, and we need to set a dynamic name to the form input,

dmx-bind:name="repeat1[{{$index}}][attendee_id]"

Lastly add a submit button.

The form code should look like this:

<form id="form1" method="post" is="dmx-serverconnect-form" action="dmxConnect/api/test/form.php">
	<div class="form-row" is="dmx-repeat" id="repeat1" dmx-bind:repeat="responses.data">
		<input id="attendee_id" dmx-bind:name="repeat1[{{$index}}][attendee_id]" type="text" class="form-control" dmx-bind:value="attendee_id">
	</div>

	<button class="btn btn-primary" type="submit">Send to Server</button>
</form>

You will now find that the number of input fields duplicates for the number of records in your browser local storage.


Server Action

Create your server action file and set the linked page and form under globals. Click Import from Form and you should see under $_POST your repeat array and the attendee_id variable.

You can now do what you like with the data. Bearing in mind to use a repeat to cycle through the multiple records that have been submitted.

4 Likes