Gravity Forms in Headless WordPress with Gatsby

12 minute read
Kellen Mace
Kellen Mace
Sr. Staff Developer Advocate

A couple weeks ago, I wrote a Gravity Forms in Headless WordPress blog post, and recorded a YouTube video to accompany it. They were both well received, but several members of the headless WordPress community told me that they’d love to learn how to work with Gravity Forms in a Gatsby app, specifically.

In this post, we’ll learn how we can use WPGraphQL, and WPGraphQL for Gravity Forms on a headless WordPress back-end to send and receive Gravity Forms data to/from a decoupled front-end Gatsby application. We’ll see how we can use the unified GraphQL data layer that Gatsby provides to query for our form data at buildtime, then use Apollo Client to submit form entries from the client.

In the Gatsby app repo, I’ll provide a suite of React components and a React hook that you can even drop into your Gatsby projects and have Gravity Forms “just work.” They’ll handle rendering out Gravity Forms forms and sending form submissions to your headless WordPress back-end.

Let’s roll! 🏎💨

Getting Started

To benefit from this post, you should be familiar with the basics of working with the command line, local WordPress development, React, Gatsby, and Apollo Client.

Here are the steps for getting set up:

  1. Set up a local WordPress site and get it running
  2. Install and activate the Gravity Forms, WPGatsby, WPGraphQL and WPGraphQL for Gravity Forms WordPress plugins.
  3. Clone down the Gatsby app repo for this project.
  4. Import the form questionnaire form. From the WordPress admin sidebar, go to Forms > Import/Export > Import Forms. Select the gravityforms-questionnaire-form.json inside Gatsby app’s folder and click the button to import it.
  5. Create an .env.development file inside of the Gatsby app’s folder. Open that file in a text editor and paste in GATSBY_WORDPRESS_API_URL=http://wpgraphqlgravtyforms.local/graphql, replacing wpgraphqlgravtyforms.local with the domain for your local WordPress site. This is the endpoint that both Gatsby and Apollo Client will use when they send requests to your WordPress back-end.
  6. Run npm install or yarn to install the dependencies.
  7. Run npm run develop to get the server running locally.
  8. You should now be able to visit http://localhost:8000/ in a web browser and see the app’s homepage.

How to Query for a Form

The gatsby-source-wordpress source plugin used by our app takes the GraphQL schema that WPGraphQL and WPGraphQL for Gravity Forms provide and adds it to Gatsby’s unified GraphQL data layer. So querying for a form looks like this:

query getForm {
  wpGravityFormsForm(formId: {eq: 4}) {
    formId
    title
    description
    formFields {
      nodes {
        id
        type
        ... on WpTextField {
          id
          type
          label
        }
        ... on WpSelectField {
          id
          type
          label
          choices {
            text
            value
          }
        }
      }
    }
  }
}

You can see that we’re asking for some data about the form itself; namely, its formId, title and description. Then under formFields > nodes (which is a GraphQL interface), we use the ... on syntax to tell GraphQL what data we’d like back for each type of field. Any field types we include here will have data returned if they exist in the form, and any we have omitted will not– they’ll appear as empty objects instead.

We can test out this query right from the GraphiQL IDE that Gatsby provides. Here’s how:

  1. With the app running, head over to http://localhost:8000/___graphql.
  2. Paste the query above into the left column, replacing “4” in eq: 4 with the ID of the form you imported.
  3. Click the ▶ button to execute the query.
  4. See the results returned in the right column.

Check out the WPGraphQL for Gravity Forms readme for more documentation on this query, as well as other queries and mutations the plugin offers. Just note that many of the fields will have different names and input fields (such as wpGravityFormsForm instead of gravityFormsForm). That’s because Gatsby modifies the WPGraphQL schema a bit before adding it to its unified GraphQL data layer schema.

Query for a Form in our App

Now that we know what a query for a form looks like let’s see how we can use it in our Gatsby app.

Open up gatsby-node.js.

const path = require("path");

exports.createPages = async ({ actions }) => {
  const { createPage } = actions;
  const questionnaireTemplate = path.resolve(`src/templates/questionnaire.tsx`);

  // Create Questionnaire page, and pass the Gravity Forms form ID to it.
  createPage({
    path: `/questionnaire`,
    component: questionnaireTemplate,
    context: {
      formId: 4,
    },
  });
};

Notice that we call the createPage() function to tell Gatsby to create a page at /questionnaire using the src/templates/questionnaire.tsx template, and that we pass in a formId of 4 for the component’s context.

Go ahead and swap out this form ID with the ID of the form you imported.

Now try restarting the local dev server, then navigating to http://localhost:8000/questionnaire. You should see the form’s title, description and fields displayed in all their barely-even-styled-at-all glory! ????

Screenshot of a rendered Gravity Forms form

But where’s all this form data-fetching magic happening? Let’s dig a bit deeper. Open up the src/templates/questionnaire.tsx. page template.

export default function Questionnaire({ data }: Props) {
  const { wpGravityFormsForm: form } = data;

  return (
    <main>
      <h1>{form.title}</h1>
      <p>{form.description}</p>
      <GravityForm form={form} />
    </main>
  );
}

export const query = graphql`
  query getForm($formId: Int!) {
    wpGravityFormsForm(formId: { eq: $formId }) {
      ...GravityFormFields
    }
  }
`;

You’ll see that we’re exporting a graphql tagged template literal containing our getForm GraphQL query. It accepts formId as an argument, then fetches the form with that ID.

The ...GravityFormFields syntax makes use of this GraphQL fragment defined in src/components/GravityFormsForm.tsx:

export const GRAVITY_FORM_FIELDS = graphql`
  fragment GravityFormFields on WpGravityFormsForm {
    formId
    title
    description
    button {
      text
    }
    confirmations {
      isDefault
      message
    }
    formFields {
      nodes {
        id
        type
        ...AddressFieldFields
        ...CheckboxFieldFields
        # etc.
      }
    }
  }
`;

It specifies what data we want to fetch for the form. Inside, it leverages even more fragments– one for each type of field. You can see those individual field fragments in each file inside of the src/components/GravityFormsFields folder.

These GraphQL fields could have all been hardcoded in the src/templates/questionnaire.tsx file, but using GraphQL fragments allows us to co-locate each component’s data requirements with that component itself. That way, things are more organized.

Render the Form

Now that we know how the form data is being queried and passed into the Questionnaire page component, let’s see how we can use that data to render our form.

Head back over to src/templates/questionnaire.tsx. You’ll see that the form’s title and description render inside of h1 and p tags, respectively, and then a <GravityForm /> component is rendered, with the form passed to it as a prop:

<main>
  <h1>{form.title}</h1>
  <p>{form.description}</p>
  <GravityForm form={form} />
</main>

Open src/components/GravityForm.tsx, where the GravityForm component is defined, and you’ll see that it renders a GravityFormsForm component, which is wrapped in a GravityFormProvider context provider:

<GravityFormProvider>
  <GravityFormsForm {...props} />
</GravityFormProvider>

Don’t worry about GravityFormProvider just yet– we’ll learn about that in the next section. For now, let’s focus on the GravityFormsForm component rendered inside of it. Navigate to src/components/GravityFormsForm.tsx next.

GravityFormsForm accepts form as a prop and renders an HTML <form> element with the form fields, any error messages, and the submit button inside. You’ll notice that it also contains a handleSubmit function to serve as the onSubmit event handler for our form. When the form is submitted, the submitForm mutation (defined at the top of the file) executes with formId and fieldValues passed in as variables.

Next, let’s take a look at how our fields are rendering. Inside of the <form>, we map over the formFields and render a GravityFormsField component for each field:

{formFields.map(field =>
  <GravityFormsField
    key={field?.id}
    field={field as FormField}
    fieldErrors={getFieldErrors(Number(field?.id))}
  />
)}

Let’s keep following this trail and head over to src/components/GravityFormsField.tsx to check out the GravityFormsField component. You’ll see that it’s little more than a switch() statement:

export default function GravityFormsField({ field, fieldErrors }: Props) {
  switch (field.type) {
    case "address":
      return <AddressField field={field} fieldErrors={fieldErrors} />;
    case "checkbox":
      return <CheckboxField field={field} fieldErrors={fieldErrors} />;
    case "date":
      return <DateField field={field} fieldErrors={fieldErrors} />;
    // etc.
  }
}

The appropriate field component is rendered out, depending on the value of field.type. When field.type encounters an unsupported field, a “Field type not supported” message appears instead.

Render the Fields

From here, you can peruse all of the individual field components inside of the src/components/GravityFormsFields folder to see how they work. All of them follow the same pattern. They:

  1. Define their data requirements in an exported GraphQL fragment (which get leveraged inside of src/components/GravityFormsForm.tsx, as mentioned previously)
  2. Define the field component, which accepts these props:
    field (the data about this field)
    fieldErrors (any errors specific to this field)
    …and returns JSX for the field
  3. Use the useGravityForm() custom React hook and
    – Use its state object to get the current value for this field
    – Call its dispatch function to update the field’s value in state

“Wait, where in blazes did this custom useGravityForm() React hook come from?!”

– You, just now

I’m glad you asked! Let’s find out –

Managing our Form State

Remember earlier when we saw that GravityFormProvider context provider in src/components/GravityForm.tsx? That, and the custom useGravityForm() hook are defined in src/hooks/useGravityForm.tsx. Let’s take a look at that file next to understand better how to manage our form state.

Scroll down to GravityFormProvider. This is a React context provider that uses React’s useReducer() and passes down state and dispatch as its value:

export function GravityFormProvider({ children }: { children: ReactNode }) {
  const [state, dispatch] = useReducer(reducer, DEFAULT_STATE);

  return (
    <GravityFormContext.Provider value={{ state, dispatch }}>
      {children}
    </GravityFormContext.Provider>
  );
}

When dispatch() is called from inside of our field components, the reducer() function in this file determines how the form state should update. The reducer runs a switch() on the type of action that was dispatched and updates the form state accordingly using the action.fieldValue data that passed in:

switch (action.type) {
  case ACTION_TYPES.updateAddressFieldValue: {
    const { id, addressValues } = action.fieldValue as AddressFieldValue;
    return [...getOtherFieldValues(id), { id, addressValues }];
  }
  case ACTION_TYPES.updateCheckboxFieldValue: {
    const { id, checkboxValues } = action.fieldValue as CheckboxFieldValue;
    return [...getOtherFieldValues(id), { id, checkboxValues }];
  }
  // etc.
}

Submitting Forms

Try submitting a few form entries yourself. After the form submits, it will be removed from the UI and replaced with the “thank you” confirmation message for our form.

Back in the WordPress admin, you can navigate to the Gravity Forms Entries page for our form and see your new entries listed. Try clicking on a few of them and confirming that the saved values match what you had entered into the form.

Error Handling

Our Gatsby app handles two types of errors:

Request or Server Errors

These are errors that prevent the form entry from being saved. Some examples:

  • The user’s network connection dropped out
  • The WordPress back-end threw a 500 Internal Server Error
  • The request was rejected because only logged-in users with the proper permissions are allowed to submit form entries for that particular form

If any of these errors occur, Apollo Client will return an error object. Our app will display errors at the bottom of the form if errors exist, just above the submit button.

To see this error handling in action, you can set your network connection to offline in the browser DevTools and then attempt to submit the form while offline.

Field Validation Errors

Inside the GravityFormsForm component, we check data.submitGravityFormsForm.errors to see if the server returns any validation errors. If we have field validation errors, we call the getFieldErrors() helper function to pull out the errors and pass them through to that particular field that failed validation. The error message text is displayed directly below that field, so the user knows why the field value they entered is invalid.

To test this locally, you can use the “Short Strings Only” field at the bottom of the imported form. In the Gravity Forms admin UI, we’ve configured that field to allow strings with a maximum length of 5 characters. So if you enter more than five characters into it, then try to submit the form, you’ll see the field validation error text appear below that field.

What’s Missing?

This suite of React components and custom hook are a starting point. You can drop them into your project and get up and running with Gravity Forms forms quickly in a Gatsby app, but there are some features they don’t provide. Some examples:

  • Client-side validation (beyond the built-in validation the browser performs on simple, single-input fields)
  • Support for Gravity Forms’ Conditional Logic rules
  • Rendering an existing Gravity Forms entry and allowing the user to update its field values
  • Support for all field types (see the section below for more details)

Which Fields are Supported?

We’re using the submitGravityFormsForm mutation that WPGraphQL for Gravity Forms provides to keep things simple. This mutation works excellent for allowing us to submit forms with some field types, such as inside of our project’s src/components/GravityFormsFields folder. However, it does not work for all field types that the WPGraphQL for Gravity Forms plugin supports.

If you want to use other field types, you would instead need to implement a more complex process that involves firing off multiple mutations to build a draft entry incrementally, then finally submit it. This is because currently, the GraphQL specification does not support input union types. You can learn more about that technical limitation by reading this GitHub issue thread and more about the alternative submission process in the WPGraphQL for Gravity Forms readme.

Hide Unsupported Fields in the WordPress Admin

Since not all field types support this approach, you may want to limit the Gravity Forms fields displayed in the WordPress admin to only the supported ones. This way, you’ll know that the content creators on the site can only choose fields that the headless app supports. You can do that using this plugin I wrote:

Gravity Forms Fields Allowlist

Just modify the list of ALLOWED_FIELDS inside of gravityforms-fields-allowlist.php to include the ones you want to be displayed in the WordPress admin, then install and activate the plugin.

How Can I Use This in My Gatsby Projects?

  1. Copy and paste src/hooks/useGravityForm.tsx, and all the components inside of src/components into your codebase.
  2. Mimic the code in gatsby-node.js to create a new page and pass in a formId as context to that page component.
  3. Copy the exported graphql query in src/templates/questionnaire.tsx and paste it into your page component file.
  4. Inside of the page component that receives the data.wpGravityFormsForm prop, render the <GravityForm form={form} /> component.
  5. If you’re using TypeScript, set up GraphQL Code Generator to generate the TypeScript types stored in generated/graphql.ts and used throughout this app. A video and blog post are available that walk through this process.

Wrapping Up

Thanks for sticking with me! I hope this post and the code repos provided are helpful as you implement Gravity Forms forms in your headless WordPress + Gatsby applications. Please reach out and let us know how it goes!