Question

The Page Analytics I use gathers the form data automatically. Gravity Forms create tag without any name attribute. I am trying to figure out a way to assign form tag a name attribute. The closest I have reached is this example:

<?php
add_filter("gform_form_tag", "form_tag", 10, 2);
function form_tag($form_tag, $form){
if ($form["id"] == 3){
   $form_tag = preg_replace("|action='(.*?)'|", "action='custom_handler.php'", $form_tag);
   return $form_tag;
   }
}
?>

But I am not sure how to use preg_replace to create a name attribute for form in question.

Was it helpful?

Solution

I figured out a solution to suite myself. Sharing it for any other troubled soul. for me all I wanted was to add a name attribute for the forms so that my analytics picks up something understandable instead of ids like form-1234 so I browsed plugin/gravityforms/forms_display.php and edited it where it creates a new form tag. can be found between line 435 to 440. created a new variable to hold value of form title, edited it to remove spaces. and inserted it to the form tag string.

//Edited For Analytics
        $cm_form_name = str_replace(" ", "-", $form['title']);
        $form_string .= apply_filters("gform_form_tag_{$form_id}", apply_filters("gform_form_tag", "<form method='post' enctype='multipart/form-data' {$target} id='gform_{$form_id}' name='{$cm_form_name}' {$form_css_class} action='{$action}'>", $form), $form);
        //End Editing
        //Orginal String
        //$form_string .= apply_filters("gform_form_tag_{$form_id}", apply_filters("gform_form_tag", "<form method='post' enctype='multipart/form-data' {$target} id='gform_{$form_id}' {$form_css_class} action='{$action}'>", $form), $form);

OTHER TIPS

I wrote a plugin that also makes adding a name attribute (or modifying/adding/removing any other attribute for the form tag) a breeze.

http://gravitywiz.com/gravity-forms-tag-editor/

Here's an example for adding the name attribute:

new GW_Tag_Editor( array(
    'tag'  => 'form',
    'name' => 'form_{formId}',
) );

I had a slightly different goal, but thanks to Jeff's idea I came up with the following approach that I think is worth sharing.

It appends a sanitized form name data attribute to the form tag, without touching any other attributes.

function add_form_name_data_attr($form_tag, $form){
    $form_tag = str_replace('>', ' data-form-name="' . sanitize_title($form['title']) . '">', $form_tag);

    return $form_tag;
}
add_filter('gform_form_tag', 'add_form_name_data_attr', 10, 2);

I can then use that data attribute in JavaScript to differentiate the various forms when calling a certain analytics API.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top