sveltekit-superforms
sveltekit-superforms copied to clipboard
Proxy object in nested array
Description
Hello, I have a form with <input type="date">, I'm using a dateProxy to convert it to the right type, that's working great. The issue I'm having is I have this zod object:
workDone: z
.object({
type: z
.string()
.nullish(),
date: z
.date()
.nullish(),
hour: z
.number()
.nullish(),
worker: z
.string()
.nullish(),
})
.array()
This Zod object is an array, because I have an Add button for creating additional rows for user to submit. The issue is I don't know how to reference inputs that are in the array in the proxy function.
Here is the loop I'm using to display the array inputs.
{#each $formData.workDone as _, i}
<Form.Field {form} name="workDone.date">
<Form.Control let:attrs>
<Form.Label>Datum</Form.Label>
<Input
{...attrs}
bind:value={$formData.workDone[i].date}
type="date"
class="focus-visible:ring-2 focus-visible:ring-offset-0 focus-visible:ring-primary/30 focus-visible:border-primary/70"
/>
</Form.Control>
<Form.FieldErrors />
</Form.Field>
{/each}
I tried creating this dateProxy, but I'm not quite sure how to get it working. Would be glad for some help, thank you :)
const workDoneDateProxy = dateProxy(form, 'workDone.date', { format: 'date', empty: 'null' });
Hello, since you're using Formsnap, I'm not exactly sure how to handle this. You should have dataType: 'json' enabled at least, since it's about nested data. If you can't figure it out, try asking in the Formsnap discord: https://discord.com/channels/1025195801095458887/1148992561130786888
Hello, thanks for the asnwer, I asked the same question in the formsnap discord, no answer yet. But I do have dataType: 'json' set.
I found that if I set the dateProxy manually like this: const workDoneDateProxy = dateProxy(form, 'workDone[0].date', { format: 'date', empty: 'null' }); it does work for the first item of the input array. So the question for me probably is how to set the dateProxy dynamically for the array items.
Any ideas how to do that? Thank you.
You could make a reactive statement that creates the proxies, and use them in the each loop.
Would you mind showing me a quick example of how to do that? Thank you so much ♥
It's not a quick example (nested data, array in component, proxy), but here you are: https://www.sveltelab.dev/ifdh4vfvtdp38rl?files=.%2Fsrc%2Froutes%2F%2Bpage.svelte%2C.%2Fsrc%2Froutes%2FDateInput.svelte%2C.%2Fsrc%2Froutes%2F%2Bpage.server.ts
Thank you so much, works great, haven't thought about using the index as prop for a dateProxy component.