Programmatically add Gravity Forms

Recently I was asked by an architect at a client to prove a persistent Gravity Forms form could be added programmatically with the possibility to maintain sorting and renaming labels of fields.

I’m sharing the basic proof of concept on how to programmatically add Gravity Forms for other developers because there is very little to be found on the topic. The code is by no means complete, the DocBlocks are there but they’re just the default automatically generated ones and the methods could be better. Alas, thats how quick PoCs tend to go.

I’ve posted the code as a Gist. Be my guest to use it. If there’s interest for it I’ll setup a Github repo.

The code is in form of a small plugin that provides a class to throw an array at. Here’s how you would do that:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
<?php
add_action( 'admin_head', 'init_ugf' );
/**
* [init_ugf description]
*
* @return [type] [description]
*/
function init_ugf() {
$screen = get_current_screen();
if ( $screen->id != 'toplevel_page_gf_edit_forms' ) {
return;
}
$gf_contact_form = array (
'title' => 'Contact',
'fields' => array (
array (
'id' => 1,
'label' => 'Name',
'adminLabel' => '',
'type' => 'name',
'isRequired' => true,
'inputs' => array (
array (
'id' => 1.3,
'label' => 'First',
'name' => '',
),
array (
'id' => 1.6,
'label' => 'Last',
'name' => '',
),
),
),
array (
'id' => 2,
'label' => 'Email',
'adminLabel' => '',
'type' => 'email',
'isRequired' => true,
),
array (
'id' => 3,
'label' => 'Subject',
'adminLabel' => '',
'type' => 'text',
'isRequired' => true,
),
array (
'id' => 4,
'label' => 'Message',
'adminLabel' => '',
'type' => 'textarea',
'isRequired' => true,
),
),
'is_active' => '1',
'date_created' => date( 'Y-m-d H:i:s' ),
);
$ugf = new ProgrammaticallyAddGravityForm();
$ugf->SetForm( $gf_contact_form );
}
view raw add-form.php hosted with ❤ by GitHub

Here’s the full plugin Gist.

WordPress debug without E_STRICT warnings?

Some plugins are still not E_STRICT safe. While debugging WordPress sites that may block you from finding bugs you are trying to find due to headers already being send.

Place this in your mu-plugins folder to disable E_STRICT warnings while debugging:

1 2 3
<?php
if ( defined( 'WP_DEBUG' ) && WP_DEBUG )
error_reporting( E_ALL & ~E_STRICT );

Fixing the E_STRICT warnings is of course the better option but so many exist, even in very popular plugins like WooCommerce.