momentum-modal icon indicating copy to clipboard operation
momentum-modal copied to clipboard

Problem with Inertia forms

Open anscharivs opened this issue 1 year ago • 2 comments

There is a problem using Inertia forms inside a modal.

When some field does not pass the validation of the request in the backend (with a Form Request, for example), the modal reloads completely and does not save the content of the fields. The form.errors object is also empty. Using preserveState does not work either.

Steps to reproduce it:

  • Have a form inside a modal:
<script setup>
    import ModalMomentum from '@/MyComponents/ModalMomentum.vue';
    import { useForm } from '@inertiajs/vue3';

    const form = useForm({
        name: null,
    });

    const store = () => {
        form.post(route('test.store'), {
            preserveState: true,
        })
    }
</script>

<template>
    <ModalMomentum>
        <form @submit.prevent="store">
            <input id="name" type="text" v-model="form.name">
            <p v-if="form.errors">
                {{ form.errors.name }}
            </p>
            <button type="submit">Save</button>
        </form>
    </ModalMomentum>
</template>
  • Have a validation rule:
<?php

use Illuminate\Foundation\Http\FormRequest;

class StoreRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name' => 'required|string|max:1',
        ];
    }

}
  • Enter a value that breaks validation (in this case, a string longer than 1 character).

package.json:

    "devDependencies": {
        "vue": "^3.3",
    },
    "dependencies": {
        "@inertiajs/vue3": "^1.0.9",
        "momentum-modal": "^0.2.0",
    }

anscharivs avatar Jul 14 '23 21:07 anscharivs

I'm not sure if this will help you, but I've experienced similar weirdness like this before, and what would end up resolving things is to completely wipe out the node_modules directory and package-lock.json and perform a fresh npm i.

What I do is add a "flush" script in my package.json:

"scripts": {
      "dev": "vite",
      "build": "vite build",
      "flush": "rm -rf node_modules package-lock.json && npm i && npm run dev"
},

And then whenever I want to "reboot" things as mentioned above, I simply run npm run flush for convenience.

The other thing to verify that you are using the correct axios version (should be 1.2.0). I've been down this road a couple of times in projects wondering why the inertia forms aren't submitting/validating correctly, and the above "clean re-install" would resolve it.

jaspertey avatar Aug 15 '23 22:08 jaspertey