function date_get_nested_elements in Date 7
Same name and namespace in other branches
- 6.2 date_api.module \date_get_nested_elements()
Return the nested form elements for a field by name. This can be used either to retrieve the entire sub-element for a field by name, no matter how deeply nested it is within fieldgroups or multigroups, or to find the multiple value sub-elements within a field element by name (i.e. 'value' or 'rrule'). You can also use this function to see if an item exists in a form (the return will be an empty array if it does not exist).
The function returns an array of results. A field will generally only exist once in a form but the function can also be used to locate all the 'value' elements within a multiple value field, so the result is always returned as an array of values.
For example, for a field named field_custom, the following will pluck out the form elements for this field from the node form, no matter how deeply it is nested within fieldgroups or fieldsets:
$elements = content_get_nested_elements($node_form, 'field_custom');
You can prefix the function with '&' to retrieve the element by reference to alter it directly:
$elements = &content_get_nested_elements($form, 'field_custom'); foreach ($elements as $element) { $element['#after_build'][] = 'my_field_afterbuild'; }
During the #after_build you could then do something like the following to alter each individual part of a multiple value field:
$sub_elements = &content_get_nested_elements($element, 'value'); foreach ($sub_elements as $sub_element) { $sub_element['#element_validate'][] = 'custom_validation'; }
Parameters
$form: The form array to search.
$field_name: The name or key of the form elements to return.
Return value
An array of all matching form elements, returned by reference.
File
- date_api/
date_api.module, line 2068 - This module will make the date API available to other modules. Designed to provide a light but flexible assortment of functions and constants, with more functionality in additional files that are not loaded unless other modules specifically include them.
Code
function &date_get_nested_elements(&$form, $field_name) {
$elements = array();
foreach (element_children($form) as $key) {
if ($key === $field_name) {
$elements[] =& $form[$key];
}
else {
if (is_array($form[$key])) {
$nested_form =& $form[$key];
if ($sub_elements =& date_get_nested_elements($nested_form, $field_name)) {
$elements = array_merge($elements, $sub_elements);
}
}
}
}
return $elements;
}