Preserving form state on validation errors only? #1183
-
I'd like to override local state when the form submit is successful, and preserve local state when the submit fails. The idea is that if the backend makes any changes to the model state, these would be reflected on the frontend after clicking Save. Is this possible? My use-case: I'm using Inertia form helper to submit a form. When the form submits, the backend will redirect back to the form page itself - either with validation errors or the updated model. The tricky part is that when the model is updated by the backend, certain model properties are auto-generated/calculated. When using the default Below is a trimmed-down version of what I'm trying to do. The backend will aut-generate the I know I can manually update the <template>
<div>
<form @submit.prevent="onSubmit">
<p>Foo: {{ form.foo }}</p>
<!-- This will not update after successful form submit -->
<p>Number: {{ form.number }}</p>
<!-- This does update after successful form submit -->
<p>Number: {{ props.model.number }}</p>
<p>
Foo: <br />
<input v-model="form.foo" type="text" />
</p>
<p>
Number (will be auto-generated if left empty): <br />
<input v-model="form.foo" type="text" />
</p>
<hr />
<button class="btn btn-primary">Submit</button>
</form>
</div>
</template>
<script setup>
import { defineProps, inject } from 'vue'
import { useForm } from '@inertiajs/inertia-vue3'
const route = inject('route')
const props = defineProps({
model: {
default: () => {},
type: Object,
},
})
const form = useForm(props.model)
const onSubmit = () => {
form.patch(route('test')) // can I set { preserveState: false } only when the submit is successful?
}
</script> |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Looks like this is totally possible! I can't believe I missed this when reading the docs: preserveState: (page) => Object.keys(page.props.errors).length > 0 However, there is an undocumented (only documented in changelog) shortcut: preserveState: "errors" |
Beta Was this translation helpful? Give feedback.
Looks like this is totally possible! I can't believe I missed this when reading the docs:
However, there is an undocumented (only documented in changelog) shortcut:
preserveState: "errors"