inertia-laravel icon indicating copy to clipboard operation
inertia-laravel copied to clipboard

How do you pass form errors into a child component

Open justageek opened this issue 2 years ago • 1 comments

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.

justageek avatar Sep 30 '22 21:09 justageek

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.

SuperDJ avatar Oct 03 '22 20:10 SuperDJ

I use something like this :

  1. I have a Form component to which I pass the current Inertia useForm object
<Form @submit.prevent="submit" :form="form">
  <Input name="lastname" ... />
</Form>
  1. The Form component receives the form props and exposes it
<script setup>
const props = defineProps({
  form: Object,
});
defineExpose({ form: props.form });
</script>
  1. 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>

qbuache avatar Nov 14 '22 14:11 qbuache

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.

crnkovic avatar Jan 16 '23 13:01 crnkovic

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!

jessarcher avatar Sep 08 '23 01:09 jessarcher