Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions packages/react/test-app/Pages/FormHelper/Data.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { useForm, usePage } from '@inertiajs/react'
import { useEffect, useState } from 'react'

export default ({ errors }: { errors?: { name?: string; handle?: string } }) => {
const form = useForm({
name: 'foo',
handle: 'example',
remember: false,
custom: {},
})

const page = usePage()
Expand Down Expand Up @@ -33,6 +35,23 @@ export default ({ errors }: { errors?: { name?: string; handle?: string } }) =>
form.setDefaults('name', 'single value')
}

const addCustomOtherProp = () => {
form.setData((prevData) => ({
...prevData,
custom: {
...prevData.custom,
other_prop: 'dynamic_value',
},
}))
}

const [formDataOutput, setFormDataOutput] = useState('')

// Effect to watch form.data and update formDataOutput
useEffect(() => {
setFormDataOutput(JSON.stringify(form.data))
}, [form.data])

return (
<div>
<label>
Expand Down Expand Up @@ -69,6 +88,18 @@ export default ({ errors }: { errors?: { name?: string; handle?: string } }) =>
</label>
{form.errors.remember && <span className="remember_error">{form.errors.remember}</span>}

<label>
Accept Terms and Conditions
<input
type="checkbox"
id="accept_tos"
name="accept_tos"
onChange={(e) => form.setData('accept_tos', e.target.checked)}
checked={!!form.data.accept_tos}
/>
</label>
{form.errors.accept_tos && <span className="accept_tos_error">{form.errors.accept_tos}</span>}

<button onClick={submit} className="submit">
Submit form
</button>
Expand All @@ -90,7 +121,15 @@ export default ({ errors }: { errors?: { name?: string; handle?: string } }) =>
Reassign single default
</button>

<button onClick={addCustomOtherProp} className="add-custom-other-prop">
Add custom.other_prop
</button>

<span className="errors-status">Form has {form.hasErrors ? '' : 'no '}errors</span>

<div id="form-data-output" data-test-id="form-data-output" style={{ display: 'none' }}>
{formDataOutput}
</div>
</div>
)
}
19 changes: 14 additions & 5 deletions packages/svelte/src/useForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,10 @@ export default function useForm<TForm extends FormDataType<TForm>>(
let recentlySuccessfulTimeoutId: ReturnType<typeof setTimeout> | null = null
let transform = (data: TForm) => data as object

const store = writable<InertiaForm<TForm>>({
...(restored ? restored.data : data),
const initialData = restored ? restored.data : cloneDeep(defaults)

const formObject: InertiaForm<TForm> = {
...initialData,
isDirty: false,
errors: (restored ? restored.errors : {}) as FormDataErrors<TForm>,
hasErrors: false,
Expand All @@ -89,7 +91,10 @@ export default function useForm<TForm extends FormDataType<TForm>>(
})
},
data() {
return Object.keys(data).reduce((carry, key) => {
return (Object.keys(this) as Array<FormDataKeys<TForm>>).reduce((carry, key) => {
if (RESERVED_KEYS.includes(key)) {
return carry
}
return set(carry, key, get(this, key))
}, {} as TForm)
},
Expand Down Expand Up @@ -257,9 +262,13 @@ export default function useForm<TForm extends FormDataType<TForm>>(
cancel() {
cancelToken?.cancel()
},
} as InertiaForm<TForm>)
} as InertiaForm<TForm>

const store = writable<InertiaForm<TForm>>(formObject)

const RESERVED_KEYS = Object.keys(formObject).filter((key) => !(key in initialData))

store.subscribe((form) => {
store.subscribe((form: InertiaForm<TForm>) => {
if (form.isDirty === isEqual(form.data(), defaults)) {
form.setStore('isDirty', !form.isDirty)
}
Expand Down
30 changes: 30 additions & 0 deletions packages/svelte/test-app/Pages/FormHelper/Data.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
name: 'foo',
handle: 'example',
remember: false,
custom: {},
})

const submit = () => {
Expand Down Expand Up @@ -33,6 +34,22 @@
const reassignSingle = () => {
$form.defaults('name', 'single value')
}

// New functions for dynamic properties
const addAcceptTos = () => {
$form.accept_tos = true // Add root-level dynamic property
}

const addCustomOtherProp = () => {
$form.custom.other_prop = 'dynamic_value' // Add nested dynamic property
}

// Reactive property to hold the stringified form.data() output
import { writable } from 'svelte/store'
const formDataOutput = writable('')

// Watch $form.data() and update formDataOutput
$: formDataOutput.set(JSON.stringify($form.data()))
</script>

<div>
Expand All @@ -58,6 +75,14 @@
<span class="remember_error">{$form.errors.remember}</span>
{/if}

<label>
Accept Terms and Conditions
<input type="checkbox" id="accept_tos" name="accept_tos" on:change={() => ($form.accept_tos = true)} />
</label>
{#if $form.errors.accept_tos}
<span class="accept_tos_error">{$form.errors.accept_tos}</span>
{/if}

<button on:click={submit} class="submit">Submit form</button>

<button on:click={resetAll} class="reset">Reset all data</button>
Expand All @@ -67,5 +92,10 @@
<button on:click={reassignObject} class="reassign-object">Reassign default values</button>
<button on:click={reassignSingle} class="reassign-single">Reassign single default</button>

<button on:click={addCustomOtherProp} class="add-custom-other-prop">Add custom.other_prop</button>

<span class="errors-status">Form has {$form.hasErrors ? '' : 'no '}errors</span>

<!-- Hidden div to display form.data() output for Playwright -->
<div id="form-data-output" data-test-id="form-data-output" style="display: none">{$formDataOutput}</div>
</div>
11 changes: 9 additions & 2 deletions packages/vue3/src/useForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,10 @@ export default function useForm<TForm extends FormDataType<TForm>>(
let recentlySuccessfulTimeoutId = null
let transform = (data) => data

const initialData = restored ? restored.data : cloneDeep(defaults)

const form = reactive({
...(restored ? restored.data : cloneDeep(defaults)),
...initialData,
isDirty: false,
errors: (restored ? restored.errors : {}) as FormDataErrors<TForm>,
hasErrors: false,
Expand All @@ -73,7 +75,10 @@ export default function useForm<TForm extends FormDataType<TForm>>(
wasSuccessful: false,
recentlySuccessful: false,
data() {
return (Object.keys(defaults) as Array<FormDataKeys<TForm>>).reduce((carry, key) => {
return (Object.keys(this) as Array<FormDataKeys<TForm>>).reduce((carry, key) => {
if (RESERVED_KEYS.includes(key)) {
return carry
}
return set(carry, key, get(this, key))
}, {} as Partial<TForm>) as TForm
},
Expand Down Expand Up @@ -258,6 +263,8 @@ export default function useForm<TForm extends FormDataType<TForm>>(
},
})

const RESERVED_KEYS = Object.keys(form).filter((key) => !(key in initialData))

watch(
form,
(newValue) => {
Expand Down
54 changes: 54 additions & 0 deletions packages/vue3/test-app/Pages/FormHelper/DataDynamic.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<script setup>
import { useForm, usePage } from '@inertiajs/vue3'
import { reactive, watch } from 'vue'

const form = useForm({
name: 'foo',
handle: 'example',
remember: false,
custom: {},
})

const page = usePage()

const submit = () => {
form.post(page.url)
}

const addCustomOtherProp = () => {
form.custom.other_prop = 'dynamic_value' // Add nested dynamic property
}

const formDataOutput = reactive({
json: '',
})
watch(
() => form.data(),
(newData) => {
formDataOutput.json = JSON.stringify(newData)
},
{ deep: true, immediate: true },
)
</script>

<template>
<div>
<label>
Full Name
<input type="text" id="name" name="name" v-model="form.name" />
</label>
<span class="name_error" v-if="form.errors.name">{{ form.errors.name }}</span>

<label>
Accept Terms and Conditions
<input type="checkbox" id="accept_tos" name="accept_tos" v-model="form.accept_tos" />
</label>
<span class="accept_tos_error" v-if="form.errors.accept_tos">{{ form.errors.accept_tos }}</span>

<button @click="submit" class="submit">Submit form</button>

<button @click="addCustomOtherProp" class="add-custom-other-prop">Add custom.other_prop</button>

<div id="form-data-output" data-test-id="form-data-output" style="display: none">{{ formDataOutput.json }}</div>
</div>
</template>
7 changes: 7 additions & 0 deletions tests/app/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,13 @@ app.post('/form-helper/data', (req, res) =>
}),
)

app.post('/form-helper/data-dynamic', (req, res) =>
inertia.render(req, res, {
component: 'FormHelper/DataDynamic',
props: {},
}),
)

app.get('/form-helper/nested', (req, res) =>
inertia.render(req, res, {
component: 'FormHelper/Nested',
Expand Down
50 changes: 50 additions & 0 deletions tests/form-component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,56 @@ test.describe('Form Component', () => {
})
})

test.describe('Dynamic Properties', () => {
test.beforeEach(async ({ page }) => {
pageLoads.watch(page)
await page.goto('/form-helper/data-dynamic')
})

test('initial data() output contains only initial properties', async ({ page }) => {
const formDataOutput = await page.locator('#form-data-output').innerText()
const data = JSON.parse(formDataOutput)

expect(data).toEqual({
name: 'foo',
handle: 'example',
remember: false,
custom: {},
})
})

test('data() output includes root-level dynamic property', async ({ page }) => {
await page.check('input[name="accept_tos"]')

const formDataOutput = await page.locator('#form-data-output').innerText()
const data = JSON.parse(formDataOutput)

expect(data).toEqual({
name: 'foo',
handle: 'example',
remember: false,
custom: {},
accept_tos: true,
})
})

test('data() output includes nested dynamic property', async ({ page }) => {
await page.getByRole('button', { name: 'Add custom.other_prop' }).click()

const formDataOutput = await page.locator('#form-data-output').innerText()
const data = JSON.parse(formDataOutput)

expect(data).toEqual({
name: 'foo',
handle: 'example',
remember: false,
custom: {
other_prop: 'dynamic_value',
},
})
})
})

test.describe('Headers', () => {
test.beforeEach(async ({ page }) => {
pageLoads.watch(page)
Expand Down
Loading