21
Extending Gravity Forms A CODE DEEP DIVE

WordPress overloading Gravityforms using hooks, filters and extending classes

Embed Size (px)

DESCRIPTION

These are the slides for my talk at WordCamp in Ottawa 2014 http://2014.ottawa.wordcamp.org/

Citation preview

Page 1: WordPress overloading Gravityforms using hooks, filters and extending classes

Extending Gravity FormsA CODE DEEP DIVE

Page 2: WordPress overloading Gravityforms using hooks, filters and extending classes

Paul Bearne @pbearneSr. Web Developer @ metronews.caPlugin author of Author Avatars List ( http://wordpress.org/plugins/author-avatars/ )WP Site Verification tool ( http://wordpress.org/plugins/wp-site-verification-tool/ )

Page 3: WordPress overloading Gravityforms using hooks, filters and extending classes

Agenda Gravity forms demo

Options overload demo

Options overload code

Metro AR demo

AR from code

Class overload demo

Class overload code

Page 4: WordPress overloading Gravityforms using hooks, filters and extending classes

DEMOGRAVITY FORMS

Page 5: WordPress overloading Gravityforms using hooks, filters and extending classes

add_filter( 'gform_pre_render', array( $this, ‘overload_gform_select_with_basecamp_user_list’), 10 );

public function overload_gform_select_with_basecamp_user_list( $form ){ $new_user_choices = null; // check we have a basecamp class $this->create_basecamp(); // lets get all basecamp users for this project $message = $this->basecamp->getPeople(); // whole account if( null == $message ){ return $form; } // loop basecamp users foreach( $message as $basecamp_user ){ $isSelected = ($this->current_user->user_email == $basecamp_user->email_address)?true:false; $new_user_choices[] = array( "text"=>esc_html( $basecamp_user->name ), "value"=>absint( $basecamp_user->id ), "isSelected"=>( bool )$isSelected, "price"=>"" ); } // loop all field and look for users foreach( $form['fields'] as &$field ){ if( in_array( $field['inputName'], $this->basecamp_user_fields ) ){ $field['choices'] = $new_user_choices; } }return $form;}

Page 6: WordPress overloading Gravityforms using hooks, filters and extending classes

add_filter( 'gform_pre_render', 'overload_gform_select_with_user_list', 10 );

function overload_gform_select_with_user_list( $form ){ $new_user_choices = null; // create an array of new option values $new_user_choices[] = array( 'text‘=>'admin', 'value'=>1, 'isSelected'=>false, 'price'=>'' ); $new_user_choices[] = array( 'text'=>'Paul Bearne', 'value'=>2, 'isSelected'=>true, 'price'=>'' ); $new_user_choices[] = array( 'text'=>'Username', 'value'=>3, 'isSelected'=>false, 'price'=>'' );

// loop all fields and look for Parameter Name foreach( $form['fields'] as &$field ){ if( in_array( $field['inputName'], 'Parameter_Name') ){ $field['choices'] = $new_user_choices; } } return $form;}

Page 7: WordPress overloading Gravityforms using hooks, filters and extending classes

DEMOMETRO AR FORM

Page 8: WordPress overloading Gravityforms using hooks, filters and extending classes

<?phprequire_once 'external-web-services/PostNewTarget.php';class mec_send_to_external_api{ private $form_id;// id of the gravity form being used function __construct() { // store the form id in options $options = get_option('basecamp_form_options'); $this->form_id = ( isset( $options['ar'] ) )?$options['ar']:1; add_action('gform_after_submission_'.$this->form_id, array( $this, mec_send_to_external_api' ), 10, 2 );); } public function mec_send_to_external_api( $entry, $form ){ // map the gravity form fields to nice names $target_name = $entry[8]; $target_short_title = $entry[14]; $target_french_short_title = $entry[15]; $target_long_title = $entry[16]; $target_french_long_title = $entry[17]; $target_image_url = $entry[2]; $target_opacity = ( float )$entry[9]; $target_overlay_type = $entry[10]; $overlay_web_url = $entry[1]; $overlay_web_internal_links = explode( ',', '' ); $overlay_web_external_links = explode( ',', '' ); $overlay_web_interactive = true; $overlay_video_url = ( 0 < strlen( $entry[12] ) )?$entry[12]:$entry[3]; $overlay_image_url = $entry[7]; $overlay_gallery = json_decode( $entry[5] ); $overlay_gallery_caption = ''; $overlay_opacity = ( float )$entry[11];

// which overtype are we loading switch ( $target_overlay_type ) { case 'gallery': $src_urls = null; if( empty( $overlay_gallery ) ){ wp_die( "No Images in upload for gallery", 'Upload failed' ); } $overlay_gallery = array_reverse($overlay_gallery,true); foreach ($overlay_gallery as $key => $image_url) { $images = null; $resizes = make_image_resizes( parse_url( $image_url, PHP_URL_PATH ) ); $folder_URL = implode( '/',( explode( '/', $image_url, -1 ) ) ); if(false == $resizes){ wp_die( "image resize failed", 'Upload failed' ); } foreach ($resizes as $row) { $images[ $row['width'] ] = $folder_URL.'/'.$row['file'] ; } $images["src"] = $image_url ; $images["caption"] = $overlay_gallery_caption ; $src_urls[] = $images; } $type = array("images" => $src_urls ); break; case 'video': $type["src"] = $overlay_video_url ; break;

Page 9: WordPress overloading Gravityforms using hooks, filters and extending classes

case 'image': $resizes = make_image_resizes( parse_url( $overlay_image_url, PHP_URL_PATH ) ); $folder_URL = implode( '/',( explode( '/', $overlay_image_url, -1 ) ) ); foreach ($resizes as $row) { $type[ $row['width'] ] = $folder_URL.$row['file'] ; } $type["src"] = $overlay_image_url ; break; case 'web': $type["src"] = $overlay_web_url ; $type["force_internal"] = $overlay_web_internal_links; $type["force_external"] = $overlay_web_external_links; $type["interactive_while_tracking"] = $overlay_web_interactive; break; default: $type = array(); // just in case break; } $metadata = array( $target_overlay_type => $type ); $metadata['tracking_opacity'] = $target_opacity; $metadata['centered_opacity'] = $overlay_opacity; $metadata['title'] = $target_short_title; $metadata['title_fr'] = $target_french_short_title; $metadata['title_long'] = $target_long_title; $metadata['title_long_fr'] = $target_french_long_title;

$response_text = ""; $date = new DateTime( "now", new DateTimeZone( "GMT" ) ); $external = new PostNewTarget(); $external->targetName = $target_name.$date->format( " Y-m-d-H:i:s" ); $external->imageLocation = $target_image_url; $external->application_metadata = json_encode( $metadata ); $response = $external->push(); $response_text = $response->getBody(); }}$mec_send_to_external_api = new mec_send_to_external_api();

Page 10: WordPress overloading Gravityforms using hooks, filters and extending classes

<?php // note the 2 at the end it tell the add action to pass 2 values to the function add_action('gform_after_submission_1', 'send_to_external_api', 10, 2 ); } function send_to_external_api( $entry, $form ){

// 2 option radio button note the 18.1 $do_publish = ( isset( $entry['18.1'] ) && true == $entry['18.1'] )? false : true; // esc text $metadata['target_name'] = esc_html( $entry[8] ); // alsway cast numbers $metadata['overlay_opacity'] = ( float )$entry[11]; // how to test for a value and switch $metadata['video_url'] = ( 0 < strlen( $entry[12] ) )?$entry[12]:$entry[3]; // URL end up commara seperated $metadata['_web_links'] = explode( ',', '' ); //file upload is a json srting so needs to decoding $metadata['gallery'] = json_decode( $entry[5] ); // if you need to switch on a value been there just look for it in array // works for selects / radio button and check boxs as you set the return values $metadata['value_set'] = ( in_array( 'look_for_me', $entry, true ) )?true:false; // encode value so we can send them $args['body'] = json_encode( $metadata ); $url = 'http://somerandomserver.com/api'; //http://codex.wordpress.org/HTTP_API //http://codex.wordpress.org/Function_Reference/wp_remote_post wp_remote_post( $url, $args ); }

Page 11: WordPress overloading Gravityforms using hooks, filters and extending classes

<?php// 175 id of form// 1 the id of form element // send 4 values to functionadd_filter("gform_field_validation_175_1", "custom_validation", 10, 4);

function custom_validation($result, $value, $form, $field){ // check have been passed is_valid as an array object // perform a test if(array_key_exists( "is_valid", $result ) && intval($value) > 10){ // make it invalid $result["is_valid"] = false; // and nice message $result["message"] = "Please enter a value less than 10"; } // return the update array return $result;}

Page 12: WordPress overloading Gravityforms using hooks, filters and extending classes

https://github.com/rocketgenius/simpleaddon/blob/master/simpleaddon.php

https://github.com/rocketgenius/simpleaddon

<?php/*Plugin Name: Gravity Forms Simple Add-OnPlugin URI: http://www.gravityforms.comDescription: A simple add-on to demonstrate the use of the Add-On FrameworkVersion: 1.1Author: RocketgeniusAuthor URI: http://www.rocketgenius.com

------------------------------------------------------------------------Copyright 2012-2013 Rocketgenius Inc.

This program is free software; you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe Free Software Foundation; either version 2 of the License, or(at your option) any later version.

This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See theGNU General Public License for more details.

You should have received a copy of the GNU General Public Licensealong with this program; if not, write to the Free SoftwareFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA*/

Page 13: WordPress overloading Gravityforms using hooks, filters and extending classes

if (class_exists("GFForms")) { GFForms::include_addon_framework();

class GFSimpleAddOn extends GFAddOn {

protected $_version = "1.1"; protected $_min_gravityforms_version = "1.7.9999"; protected $_slug = "simpleaddon"; protected $_path = "asimpleaddon/asimpleaddon.php"; protected $_full_path = __FILE__; protected $_title = "Gravity Forms Simple Add-On"; protected $_short_title = "Simple Add-On";

public function init(){ parent::init(); add_filter("gform_submit_button", array($this, "form_submit_button"), 10, 2); }

// Add the text in the plugin settings to the bottom of the form if enabled for this form function form_submit_button($button, $form){ $settings = $this->get_form_settings($form); if(isset($settings["enabled"]) && true == $settings["enabled"]){ $text = $this->get_plugin_setting("mytextbox"); $button = "<div>{$text}</div>" . $button; } return $button; }

Page 14: WordPress overloading Gravityforms using hooks, filters and extending classes

public function plugin_page() { ?> This page appears in the Forms menu <?php }

public function form_settings_fields($form) { return array( array( "title" => "Simple Form Settings", "fields" => array( array( "label" => "My checkbox", "type" => "checkbox", "name" => "enabled", "tooltip" => "This is the tooltip", "choices" => array( array( "label" => "Enabled", "name" => "enabled" ) ) ),……….

Page 15: WordPress overloading Gravityforms using hooks, filters and extending classes

public function settings_my_custom_field_type(){ ?> <div> My custom field contains a few settings: </div> <?php $this->settings_text( array( "label" => "A textbox sub-field", "name" => "subtext", "default_value" => "change me" ) ); $this->settings_checkbox( array( "label" => "A checkbox sub-field", "choices" => array( array( "label" => "Activate", "name" => "subcheck", "default_value" => true )

) ) ); }

Page 16: WordPress overloading Gravityforms using hooks, filters and extending classes

public function plugin_settings_fields() { return array( array( "title" => "Simple Add-On Settings", "fields" => array( array( "name" => "mytextbox", "tooltip" => "This is the tooltip", "label" => "This is the label", "type" => "text", "class" => "small" ) ) ) ); }

Page 17: WordPress overloading Gravityforms using hooks, filters and extending classes

public function scripts() { $scripts = array( array("handle" => "my_script_js", "src" => $this->get_base_url() . "/js/my_script.js", "version" => $this->_version, "deps" => array("jquery"), "strings" => array( 'first' => __("First Choice", "simpleaddon"), 'second' => __("Second Choice", "simpleaddon"), 'third' => __("Third Choice", "simpleaddon") ), "enqueue" => array( array( "admin_page" => array("form_settings"), "tab" => "simpleaddon" ) ) ),

);

return array_merge(parent::scripts(), $scripts); }

Page 18: WordPress overloading Gravityforms using hooks, filters and extending classes

public function styles() {

$styles = array( array("handle" => "my_styles_css", "src" => $this->get_base_url() . "/css/my_styles.css", "version" => $this->_version, "enqueue" => array( array("field_types" => array("poll")) ) ) );

return array_merge(parent::styles(), $styles); }

}

new GFSimpleAddOn();}

Page 19: WordPress overloading Gravityforms using hooks, filters and extending classes

Questions?

Page 20: WordPress overloading Gravityforms using hooks, filters and extending classes

The Add-On framework is geared towards developers building Gravity Forms Add-Ons. It has a set of classes that can be extended and make the task of creating an Add-On much simpler than before. The following documentation page should give you a good overview and it also links to a couple of sample Add-Ons that you can download from Git Hub to see things in action.http://www.gravityhelp.com/documentation/page/Add-On_Framework

The Web API allows remote programatic access to Gravity Form. It can be used for example, to implement a mobile app, or anytime you need to perform operations on your Gravity Forms site from a remote site. The following documentation page should give you a good overview:http://www.gravityhelp.com/documentation/page/Web_API

gform_pre_render –http://www.gravityhelp.com/documentation/page/Gform_pre_render

gform_field_validation - Allows custom validation to be done on a specific field.http://www.gravityhelp.com/documentation/page/Gform_field_validation

gform_after_submission - Allows tasks to be performed after a successful submission.http://www.gravityhelp.com/documentation/page/Gform_after_submission

Page 21: WordPress overloading Gravityforms using hooks, filters and extending classes

Slides@ http://www.slideshare.net/pbearneEmail: [email protected]