Code Monkey home page Code Monkey logo

wpgravitybundle's Introduction

WPGravityBundle

Headless WordPress is the future of WordPress, and WPGraphQL is at it's helm. With WPGraphQL for Gravity Forms, you can harness the power of Gravity Forms for your headless website. This package is built to complement the work done by Harness Software by giving you a React Component and a hook that will handle your form data and assemble your submission mutation for you.

Installation

To install this package simply run

npm install wpgravitybundle

The following system is recommended:

  • PHP 7.4+ || 8.0
  • WordPress 5.4.1+
  • WPGraphQL 1.9.0+
  • Gravity Forms 2.5+ (Recommend: v2.6+)
  • WPGraphQL for Gravity Forms 0.11.10
  • WPGraphQL Upload - used for File Upload

Technically, this package simply needs data in JSON format so the above is not necessary. However, the shape of this data is dependant upon the shape that WPGraphQL for Gravity Forms gives you for your data and expects upon form submission.

Use

To use this package, import the form component and the hook. The GravityForm component needs two props: form and onSubmit. Since this package is built to use with WPGraphQL for Gravity Forms WordPress plugin by Harness Software, it expects a specific json object for each field. form should be the data.wpGfForm object you receive from your query. The onSubmit prop is expecting a function.

Internally, the package will map through your fields, display them, and handle state and validation. The form values are passed into your onSubmit function when the form is submitted. They are already preformatted so that all you need to do is pass the values into your mutation as an variable.

The useGravityFormMutation hook needs your form data as well. It will use the form data to create the necessary GraphQL Mutation to submit the user's input. Just assign it a name and plug it into your preferred GraphQL client.

Example Use:

import React from 'react'
import { graphql } from 'gatsby'
import { useMutation } from "urql"
import Parser from 'html-react-parser'
import GravityForm, { useGravityFormMutation } from "wpgravitybundle"

export default function Example({ data }) {
  const form = data.wpGfForm
  const buttonClass = "btn-primary"
  const captchaSiteKey = process.env.GOOGLE_INVISIBLE_CAPTCHA_SITE_KEY
  const captchaSecretKey = process.env.GOODLE_INVISIBLE_CAPTCHA_SECRET_KEY

  const validation = [
    {
      id: 5, // id of the form field.
      regex: /[0-9]+/g, // regex you would like to validate the field with.
      message: "I don't like letters! Only numbers." // error message displayed if validation fails.
    }
  ]
  const captcha = { 
    captchaSiteKey, 
    captchaSecretKey,
    type: "Invisible" // options are "Invisible" and "Checkbox".
  }

  const gravityFormMutation = useGravityFormMutation(form)
  const SubmitForm = `${gravityFormMutation}`

  const [{ data, fetching, error }, submitForm] = useMutation(SubmitForm)

  const handleSubmit = (values: any) => {
    return submitForm(values)
  }

  if (fetching) {
    return <p>Loading... </p>
  }

  if (error) {
    return <p>There was an error submitting the form: {error.message}</p>
  }

  if (data) {
    return <p>Confirmation message here!</p>
  }

  return (
    <>
      {form && (
        <>
          <GravityForm
            form={form} // necessary
            onSubmit={handleSubmit} // necessary
            buttonClass={buttonClass} // optional
            validation={validation} // optional. For custom field value validation.
            captcha={captcha} // necessary if you are using a Captcha field.
            parser={Parser} // necessary if you are using an HTML field.
            debug={true} // will console.log form state to help you debug issues.
          />
        </>
      )}
    </>
  )
}

export const query = graphql`
  query {
      wpGfForm(databaseId: {eq: 1}) {
        id
        databaseId
        cssClass
        formFields {
          nodes {
            ... on WpTextField {
              id
              type
              cssClass
              isRequired
              label
              pageNumber
              placeholder
              size
            }
          }
        }
        submitButton {
          text
          type
        }
      }
    }
  `

Styling

Admittedly, more work could be done to make styling easier and this is something we want to do for future releases. For now, the easiest way is to take advantage of cssClass. You can query for cssClass on the form and for every form field. Each form field is wrapped in a <div className={${cssClass}}>. Certain fields have the cssClass set on the fieldset element instead.

Demos

Check out https://WPGravityBundle.com to see it in action. Example Form

Inspiration

This package was inspired by the work of Kellen Mace (https://twitter.com/kellenmace) of WP Engine and his public Github repository: https://github.com/kellenmace/gravity-forms-in-headless-wordpress-gatsby.

Say Thank You

If you enjoy using WPGravityBundle and want to say thank you, you can buy me a coffee:

Buy Me A Coffee

About the Author.

I love WordPress and React. I have been working with WordPress for 15 years, and React/Node for 4. Headless WordPress is definitely a passion of mine, and I love looking for opportunities to contribute whenever I can. If you have a WordPress/React project you'd like a hand with, please reach out to me at [email protected]!

wpgravitybundle's People

Contributors

mosesintech avatar

Stargazers

 avatar  avatar  avatar

wpgravitybundle's Issues

Add Gravity Form Classes to Form && Fields

Is your feature request related to a problem? Please describe.
In a traditional WordPress site with Gravity Forms, the form and each field, and sometimes the items in those fields, all have gf_, gfield_, gform-, ginput_, gchoice_, or field prefixed classes among other classes.

It would be good to add these classes as default to the form component and all field components.

NOTE: The addition of custom classes, as shown below, does NOT replace these default classes.

Screen Shot 2023-06-23 at 5 51 36 PM Screen Shot 2023-06-23 at 5 57 29 PM Screen Shot 2023-06-23 at 5 58 22 PM

Conditional Logic Support

Gravity Forms is powerful enough to have form fields render conditionally. This logic is supported by WPGraphQL for Gravity Forms so we should also be supporting it.

Add Honeypot Support

gfForms {
    nodes {
      hasHoneypot
    }
  }

NOTE: need to investigate If the honeypot flags a submission as spam setting:

Screen Shot 2023-06-23 at 7 01 55 PM

Field Label and Sub-Label Placement Logic

Describe the solution you'd like
All fields have support for the label string, but there is currently no support for labelPlacement or subLabelPlacement.

labelPlacement can be either "HIDDEN" or "INHERIT".
subLabelPlacement can be "INHERIT", "BELOW", "ABOVE", or null. These four map to the four options in WP: "Use Form Setting", "Below inputs", "Above inputs", and "Hidden", respectively.

Add Required Field Indicator Setting Support

Currently there is no marker for indicating required fields. By default the Gravity Form setting is Text: (Required), but can be an asterisk * or a custom string value.

gfForms {
    nodes {
      requiredIndicator # returns "TEXT", "ASTERISK", or "CUSTOM"
      customRequiredIndicator
    }
  }

This shouldn't be too difficult to add to the ${label} lines in each field.

Confirm Email Field Placeholder && Label Support

Is your feature request related to a problem? Please describe.
The Confirm Email field is currently using the placeholder value for the Email field, but not the placeholder value for the Confirm Email field. It is also just using the string 'Confirm Email' as the label, when it should come from inputs data.

... on WpEmailField {
          hasEmailConfirmation
          placeholder
          inputs {
              ... on WpEmailInputProperty {
                  placeholder
              }
          }
      }

Should be an easy fix. Something like:

const confirmPlaceholder = inputs[1].placeholder
const confirmLabel = inputs[1].label

Add Progress Bar Support for Page Field

After adding a Page field to your form, if you look at the preview you will see a progress bar that fills as you progress through the pages. Above the bar is the page you are on in a text string Step X of Y; I will call this label. Below this is the progress bar with a percentage value reflecting your progress.

Screen Shot 2023-06-23 at 5 19 37 PM

If this is added, we should also add a new prop to the GravityForm component called progressBar. I suggest this be an object shaped like this:

interface ProgressBar {
    display?: boolean // should we show the progress bar?
    color?: string // hex color progress bar should be
    label?: string // example: "Step", "Page", "Phase". Result will be `${label} ${currentPage} of ${totalPages}`. If null, hide label.
}

Phone Field Does Not Validate Input

Describe the bug
The Phone Field should validate input like every other input field. It should have default validation regex and should allow the use of custom validation rules. It should validate input for "STANDARD" phone numbers and "INTERNATIONAL" numbers.

Expected behavior
It is expected that the Phone Field should validate input.

Field Description && Description Placement Support

Describe the solution you'd like
There is currently no support for description or descriptionPlacement in any field.

descriptionPlacement can be "INHERIT", "BELOW", "ABOVE". These three map to the three options in WP: "Use Form Setting", "Below inputs", and "Above inputs", respectively. Notably there is no option for hidden, perhaps suggesting that the description should always be shown unless the description itself is empty.

Submit, Page Previous, and Page Next Buttons Image Support

Currently there is only support for Button text strings, but Gravity Forms and WPGraphQL For Gravity Forms both allow for Button type to be image and have imageUrl for the submitButton for the whole form itself, and both nextButton and previousButton in the Page field type.

There doesn't seem to be support from Gravity Forms for an image alt.

Support for more Number Field values

Is your feature request related to a problem? Please describe.
Most Number Field features are currently unsupported: numberFormat, rangeMax, rangeMin, calculationFormula, and calculationRounding.

The field currently works as a simple number field, but should also be supporting these values as well. This will require a rewrite of the validation logic, but I don't believe it should be too difficult.

Use buttonClass prop as default classes for Page buttons

Right now, a user must add classes to Custom CSS Class option in WP. But it may be the case that a user may wish to simply add the button classes to the one buttonClass prop in the GravityForm component and expect it to be spread to all buttons.

It wouldn't be a bad idea to have buttonClass be the default classes for the Page buttons. And it should be a simple fix too.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.