Skip to content

Forms

Submitting forms

While it's possible to make classic HTML form submissions with Inertia, it's not recommended since they cause full-page reloads. Instead, it's better to intercept form submissions and then make the request using Inertia.

vue
<template>
  <form @submit.prevent="submit">
    <label for="first_name">First name:</label>
    <input id="first_name" v-model="form.first_name" />
    <label for="last_name">Last name:</label>
    <input id="last_name" v-model="form.last_name" />
    <label for="email">Email:</label>
    <input id="email" v-model="form.email" />
    <button type="submit">Submit</button>
  </form>
</template>

<script>
import { router } from '@inertiajs/vue2'

export default {
  data() {
    return {
      form: {
        first_name: null,
        last_name: null,
        email: null,
      },
    }
  },
  methods: {
    submit() {
      router.post('/users', this.form)
    },
  },
}
</script>

As you may have noticed in the example above, when using Inertia, you don't typically need to inspect form responses client-side like you would when making XHR / fetch requests manually.

Instead, your server-side route / controller typically issues a redirect response. And, Of course, there is nothing stopping you from redirecting the user right back to the page they were previously on. Using this approach, handling Inertia form submissions feels very similar to handling classic HTML form submissions.

ruby
class UsersController < ApplicationController
  def create
    user = User.new(user_params)

    if user.save
      redirect_to users_url
    else
      redirect_to new_user_url, inertia: { errors: user.errors }
    end
  end

  private

  def user_params
    params.require(:user).permit(:name, :email)
  end
end

Server-side validation

Handling server-side validation errors in Inertia works a little different than handling errors from manual XHR / fetch requests. When making XHR / fetch requests, you typically inspect the response for a 422 status code and manually update the form's error state.

However, when using Inertia, a 422 response is never returned by your server. Instead, as we saw in the example above, your routes / controllers will typically return a redirect response - much like a classic, full-page form submission.

For a full discussion on handling and displaying validation errors with Inertia, please consult the validation documentation.

Form helper

Since working with forms is so common, Inertia includes a form helper designed to help reduce the amount of boilerplate code needed for handling typical form submissions.

vue
<template>
  <form @submit.prevent="form.post('/login')">
    <!-- email -->
    <input type="text" v-model="form.email" />
    <div v-if="form.errors.email">{{ form.errors.email }}</div>
    <!-- password -->
    <input type="password" v-model="form.password" />
    <div v-if="form.errors.password">{{ form.errors.password }}</div>
    <!-- remember me -->
    <input type="checkbox" v-model="form.remember" /> Remember Me
    <!-- submit -->
    <button type="submit" :disabled="form.processing">Login</button>
  </form>
</template>

<script>
import { useForm } from '@inertiajs/vue2'

export default {
  data() {
    return {
      form: useForm({
        email: null,
        password: null,
        remember: false,
      }),
    }
  },
}
</script>

To submit the form, you may use the get, post, put, patch and delete methods.

js
form.submit(method, url, options)
form.get(url, options)
form.post(url, options)
form.put(url, options)
form.patch(url, options)
form.delete(url, options)

The submit methods support all of the typical visit options, such as preserveState, preserveScroll, and event callbacks, which can be helpful for performing tasks on successful form submissions. For example, you might use the onSuccess callback to reset inputs to their original state.

js
form.post('/profile', {
  preserveScroll: true,
  onSuccess: () => form.reset('password'),
})

If you need to modify the form data before it's sent to the server, you can do so via the transform() method.

js
form
  .transform((data) => ({
    ...data,
    remember: data.remember ? 'on' : '',
  }))
  .post('/login')

You can use the processing property to track if a form is currently being submitted. This can be helpful for preventing double form submissions by disabling the submit button.

vue
<button type="submit" :disabled="form.processing">Submit</button>

If your form is uploading files, the current progress event is available via the progress property, allowing you to easily display the upload progress.

vue
<progress v-if="form.progress" :value="form.progress.percentage" max="100">
  {{ form.progress.percentage }}%
</progress>

If there are form validation errors, they are available via the errors property. When building Rails powered Inertia applications, form errors will automatically be populated when your application throws instances of ActiveRecord::RecordInvalid, such as when using #save!.

vue
<div v-if="form.errors.email">{{ form.errors.email }}</div>

NOTE

For a more thorough discussion of form validation and errors, please consult the validation documentation.

To determine if a form has any errors, you may use the hasErrors property. To clear form errors, use the clearErrors() method.

js
// Clear all errors...
form.clearErrors()

// Clear errors for specific fields...
form.clearErrors('field', 'anotherfield')

If you're using a client-side input validation libraries or do client-side validation manually, you can set your own errors on the form using the setErrors() method.

js
// Set a single error...
form.setError('field', 'Your error message.')

// Set multiple errors at once...
form.setError({
  foo: 'Your error message for the foo field.',
  bar: 'Some other error for the bar field.',
})

NOTE

Unlike an actual form submission, the page's props remain unchanged when manually setting errors on a form instance.

When a form has been successfully submitted, the wasSuccessful property will be true. In addition to this, forms have a recentlySuccessful property, which will be set to true for two seconds after a successful form submission. This property can be utilized to show temporary success messages.

To reset the form's values back to their default values, you can use the reset() method.

js
// Reset the form...
form.reset()

// Reset specific fields...
form.reset('field', 'anotherfield')

If your form's default values become outdated, you can use the defaults() method to update them. Then, the form will be reset to the correct values the next time the reset() method is invoked.

js
// Set the form's current values as the new defaults...
form.defaults()

// Update the default value of a single field...
form.defaults('email', 'updated-default@example.com')

// Update the default value of multiple fields...
form.defaults({
  name: 'Updated Example',
  email: 'updated-default@example.com',
})

To determine if a form has any changes, you may use the isDirty property.

vue
<div v-if="form.isDirty">There are unsaved form changes.</div>

To cancel a form submission, use the cancel() method.

vue
form.cancel()

To instruct Inertia to store a form's data and errors in history state, you can provide a unique form key as the first argument when instantiating your form.

vue
import { useForm } from '@inertiajs/vue2'

form: useForm('CreateUser', data)
form: useForm(`EditUser:${this.user.id}`, data)

File uploads

When making requests or form submissions that include files, Inertia will automatically convert the request data into a FormData object.

For a more thorough discussion of file uploads, please consult the file uploads documentation.

XHR / fetch submissions

Using Inertia to submit forms works great for the vast majority of situations; however, in the event that you need more control over the form submission, you're free to make plain XHR or fetch requests instead using the library of your choice.