I'm currently having problem with creating form that can be grouped using form data.
I have this form:
<form action={formAction} className="flex flex-col w-full justify-around">
<div className="relative">
<Options
data={activeUsers.users}
name="user"
id="user"
display1="firstName"
display2="lastName"
label="Employee"
htmlFor="user"
hideLabel={false}
/>
<table className="mt-5">
<thead>
<tr>
<th>Success Indicator</th>
<th>MOV</th>
<th>Aspect Of Work</th>
</tr>
</thead>
<tbody>
{inputRows.map((item: any, i: number) => (
<tr key={i}>
<td>
<input
type="text"
id="mov"
name={`test[${i}]`}
placeholder="MOV"
className="rounded-lg py-1 px-1 m-2 text-black"
required
/>
</td>
<td>
<input
type="text"
id="aspects_of_work"
name={`test[${i}]`}
placeholder="Aspect of work"
className="rounded-lg py-1 px-1 m-2 text-black"
required
/>
</td>
</tr>
))}
</tbody>
</table>
<SubmitBtn />
</div>
<p role="status">{state?.message}</p>
</form>
im expecting a form data like this:
{
user: 1,
test: [
{
mov: value here,
aspects_of_work: value here
},
{
mov: value here,
aspects_of_work: value here
}
]
}
im assuming that the property name is coming from the id property
instead I get this:
{ name: 'user', value: '1' },
{ name: 'test[0]', value: '5' },
{ name: 'test[0]', value: 'qwe' },
{ name: 'test[0]', value: 'ewq' },
{ name: 'test[1]', value: '27' },
{ name: 'test[1]', value: 'rrr' },
{ name: 'test[1]', value: 'rrr' }
I was wondering if I have to this manually using formdata API or should this be automatic. I know rails erb do this but im not sure if it should be the same way.
Im using this on NEXTJS btw.
As I've been searching. there's no really way of grouping an same named property in FormData as it will be converted to a string per documentation https://developer.mozilla.org/en-US/docs/Web/API/FormData/append.
What I've resulted to do is manipulate the formData it self but I have to setup the names of my fields.
name property have a value of STTRING-INDEX to be used later.
Logic for creating the desired output:
Before Data:
After Data:
The downside with this is in each Aspects I have to loop to convert each aspect to
Object.fromEntries