I'm using the gform_pre_render_{$int}
hook to programmatically populate one of my drop-downs. In the hooked function, I have the following within a loop...
$field['choices'][] = array(
'text' => "{$date} — {$event->post_title}, {$meta1}",
'value' => $event->post_name,
);
That works fine as-is, but I also need to add some data-
attributes for the sake of some custom Javascript... BUT... Gravity Forms doesn't seem to offer any hooks or options whatsoever for adding additional attributes. Adding 'data-mydata' => $myValue
does nothing.
I went digging through GF to se if there was somewhere I might be able to hook in, but can't find a thing. I believe GFCommon::get_select_choices()
is the method that handles individual choices, and it contains no hooks or handling for array keys other than those that are hard-coded. What I believe is needed is some changes to GF.
This is what I propose...
Any entry under the 'choices' array should allow an associative sub-array called 'attributes'... that should then be parsed and outputted into the element, allowing developers to do something like this...
$field['choices'][] = array(
'text' => "{$date} — {$event->post_title}, {$meta1}",
'value' => $event->post_name,
'attributes' => array(
'data-mydata' => $myValue,
),
);
Parsing associative arrays into attributes is as easy as using something like this (a method I wrote as part of a WordPress-centric HTML generator):
/**
* Turns an associative array into HTML-ready attribute-value pairs.
*
* Any array values which are also arrays are turned into space-delimited
* word values (in the vein of the CSS classes).
*
* @param array $atts An associative array of attributes and values.
* @return string Attribute-value pairs ready to be used in an HTML element.
*/
public static function generate_atts($atts)
{
$return='';
foreach($atts as $att=>$val) {
if ( is_array($val) || is_object($val) ) {
$return .= sprintf( '%s="%s" ',
sanitize_title_with_dashes($att),
esc_attr( implode($val,' ') )
);
}
else {
$return .= sprintf( '%s="%s" ',
sanitize_title_with_dashes($att),
esc_attr($val)
);
}
}
return $return;
}
Finally, get_select_choices()
(and any other methods that generate HTML) would need to be updated like so...
$attributes = (isset($choice['attributes']) && is_array($choice['attributes']) )
? generate_atts($choice['attributes'])
: '';
$choices.= sprintf("<option value='%s' %s %s>%s</option>", esc_attr($field_value), $attributes, $selected, esc_html($choice["text"]));
If there is another way for me to do this, I'd love to hear it... otherwise, I may need to modify GF core (as shown above) to get this functionality as it's mission critical to my current project. It's simple enough and I've tested it and it works... but if I have to modify core, I'd really want to make sure that the functionality gets incorporated into the next GF release so that my forms don't break if someone updates the GF plugin.