inertia-laravel
inertia-laravel copied to clipboard
How do you pass form errors into a child component
I have a child Vue 3 component that provides the form for a submit action, if there are validation errors, I don't know how to get those errors from the parent down into the form provided by the child so I can show them in the form.
In both the parent and child define a prop called errors. The errors
prop must be an empty object by default in the parent passed on to the child.
I use something like this :
- I have a Form component to which I pass the current Inertia useForm object
<Form @submit.prevent="submit" :form="form">
<Input name="lastname" ... />
</Form>
- The Form component receives the form props and exposes it
<script setup>
const props = defineProps({
form: Object,
});
defineExpose({ form: props.form });
</script>
- And then my Input component creates a computed value which searches for a parent with the exposed form property (which should exists, because it's supposed to be used inside of the Form component)
<template>
<div>
<input type="text" ... />
<Error v-if="form?.errors" :error="form.errors[name]" />
</div>
</template>
<script setup>
import { computed, getCurrentInstance } from "vue";
const form = computed(() => {
let depth = 0;
let parent = getCurrentInstance().parent;
while (!parent?.props?.form && depth < 20) {
parent = parent.parent;
depth++; // just to make sure we don't end up in a loop due to bad development
}
return parent.props.form;
});
</script>
You can just use errors
as a regular Vue prop and pass that into the child components:
<script setup>
import ChildComponent from './ChildComponent.vue'
defineProps(['errors'])
// or resolve from usePage().props.value.errors
</script>
<template>
<div>
<ChildComponent :errors="errors" />
</div>
</template>
However, you can also just use Inertia's form helper, it gives you access to form.errors
that you can use inside the child component.
@justageek make sure to close the issue once this is resolved.
Hi there,
Thanks for reporting the problem you are encountering, but it looks like this is a question that may be better suited for a support channel. We only use this issue tracker for reporting bugs with the library itself. If you have a question on how to use the functionality provided by this repository, you can try one of the following channels:
However, this issue will not be locked, and everyone is free to discuss solutions to your problem!