Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom: Gravity Forms WP API Submission and GF API form entry creation plus send notifications
<?php
/**
* Add WP API endpoint for form submission, then create new
* Gravity Forms entry and send notifications.
*/
// rest api endpoint for forms submission
add_action( 'rest_api_init', function () {
register_rest_route( 'ahr/v1', '/forms', array(
'methods' => 'POST',
'callback' => __NAMESPACE__ . '\\gravity_forms_endpoint',
));
});
function gravity_forms_endpoint( \WP_REST_Request $request ) {
# @TODO: sanitize inputs
# USE: sanitize_text_field()
# ensure gravity forms available !!
if (!class_exists('GFAPI')) {
wp_send_error(array(
'error' => true,
'message' => 'Gravity forms plugin not enabled'
));
}
$entry_id = insertGravityFormEntry($request->get_params());
if (is_wp_error($entry_id)) {
wp_send_json_error( array(
'error' => true,
'message' => $entry_id->get_error_message(),
'values' => $request->get_params(),
));
// wp_send_json_error($resp);
} else {
$resp = array(
'message' => 'Received these params',
'entry_id' => $entry_id,
'form' => $request->get_params(),
);
wp_send_json( $resp );
}
}
/**
* const - ID for contact-us gravity form
*/
define('GRAVITY_FORMS_CONTACT_FORM_ID', 1);
/**
* Create new gravity forms entry for contact form, and insert it.
*
* Caller needs to test response with is_wp_error.
* @thanks to https://gist.github.com/OutThisLife/bd33674bae36121a3c99
*
* To get a sample form entry, try: print_r( GFAPI::get_entry(<existing-form-entry-id>) );die();
*
* @param {array} $params - form submission params.
* @return {mixed} - Either the new Entry ID or a WP_Error instance
*/
function insertGravityFormEntry($params) {
$form = \GFAPI::get_form(GRAVITY_FORMS_CONTACT_FORM_ID);
# Build our entry
$entry = array('form_id' => $form['id']);
$entry['date_created'] = date('Y-m-d G:i');
$entry[1] = $params['name'];
$entry[2] = $params['email'];
$entry[3] = $params['organization'];
$entry[4] = $params['comment'];
$entry_id_or_wperror = \GFAPI::add_entry($entry);
if (!is_wp_error($entry_id_or_wperror)) {
$entry = \RGFormsModel::get_lead($entry_id_or_wperror);
\GFAPI::send_notifications($form, $entry, 'form_submission');
}
return $entry_id_or_wperror;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.