In this article, we will explore how to enhance Gravity Forms by automatically adding autocomplete attributes to form fields.
To add the autocomplete
attribute to Gravity Forms fields for improved accessibility, you can use the following code snippet:
/** * By default, Gravity Forms aren't accessible. This function adds autocomplete attributes to fields. * * @param mixed $content * @param mixed $field * @param mixed $value * @param mixed $lead_id * @param mixed $form_id * @return void */ function autocomplete_add_fields_wrapper( $content, $field, $value, $lead_id, $form_id ) { if ( $form_id !== 1 ) { return $content; // Break if form ID is not 1 } $lookup = array( 1 => 'name', 2 => 'tel', 3 => 'email', ); $regex = '/\<(?:input|select|textarea)\s+[^\>]+?(\s*\/?\>){1}/im'; if ( preg_match( $regex, $content, $input ) ) { $attribute = isset( $lookup[ $field->id ] ) ? $lookup[ $field->id ] : ''; $autocomplete = sprintf( ' autocomplete="%s"', esc_attr( $attribute ) ); $element = str_replace( $input[1], $autocomplete . $input[1], $input[0] ); $content = str_replace( $input[0], $element, $content ); } return $content; } add_filter( 'gform_field_content', 'autocomplete_add_fields_wrapper', 10, 5 );
In the provided code, there is a check for the $form_id
variable to ensure that the autocomplete attributes are added only for a specific form with ID 1. If the $form_id
does not match the specified form ID, the function will exit without modifying the content.
Replace the 1
in $form_id != 1
with the desired form ID. This ensures that the autocomplete attributes are added only for the specified form and not for other forms on your website.
Also, there is an array called $lookup
that contains the hardcoded field IDs and their corresponding autocomplete attributes.
To make the code work correctly for your specific form fields, you would need to update the $lookup
array with the appropriate field IDs and their corresponding autocomplete attributes.
You can identify the field IDs by inspecting the HTML source code of your form or by checking the Gravity Forms admin panel.
For example, if you have a field with ID 4 that should have the autocomplete attribute ’email’, you would modify the $lookup
array as follows:
$lookup = array( 2 => 'name', 3 => 'tel', 4 => 'email', );
Replace the values with the desired autocomplete attributes for each field ID in your form.
By updating the $lookup
array accordingly, the code will assign the correct autocomplete attributes based on the field IDs you specify.