I was experiencing an error with nested groups not being rendered. So I debugged the code down to the field_group_fields_nest() function. Knowing the source of the problem I looked for updates. The current dev of this module does solve the error I experienced but I had already seen that this function could be written a lot easier.
So I decided to rewrite the function and post it here as an improvement:
function field_group_fields_nest(&$root_element) {
// Create all groups and keep a flat list of references to these groups.
$group_references = array();
foreach ($root_element['#groups'] as $group_name => $group) {
$root_element[$group_name] = array();
$group_references[$group_name] = &$root_element[$group_name];
}
// Move all children to their parents. Use the flat list of references for
// direct access as we don't know where in the root_element hierarchy the
// parent currently is situated.
foreach ($root_element['#group_children'] as $child_name => $parent_name) {
// Block denied fields (#access) before they are put in groups.
if (!isset($root_element[$child_name]['#access']) || $root_element[$child_name]['#access']) {
// Use a reference as this may be a group, not a field.
$group_references[$parent_name][$child_name] = &$root_element[$child_name];
}
// The child has been copied to its parent: remove it from the root element.
unset($root_element[$child_name]);
}
// Bring extra element wrappers to achieve a grouping of fields.
// This will mainly be prefix and suffix altering.
foreach ($root_element['#groups'] as $group_name => $group) {
field_group_pre_render($group_references[$group_name], $group, $root_element);
}
}
Advantages;
- no nested loops.
- no recursion.
- (consequence of the first 2) more performant.
- field_pre_render called when the whole hierarchy has been built.
- less side effects: #group_children (and #groups) array elements remain unaffected.
I think this will be a nice improvement of your code.
Comments
Comment #1
fietserwinFurther improving the code:
- the calling function can be cleaned
- documentation adapted to the new code
Comment #2
Stalski CreditAttribution: Stalski commentedWe'll give it a go. The code is looking good and I think this might work for all cases.
I'll respond asap.
Comment #3
Stalski CreditAttribution: Stalski commentedSeems to work just fine. The memory usage and query time is the same but the new code looks better and easier to maintain.
The recursion by reference is easier to read. So thx!
Comment #4
Stalski CreditAttribution: Stalski commentedDid some additional testing. No problem what so ever.
Fixed and committed.