I've got an input field in an entity form which needs quite a bit of extra documentation. This documentation is long and needs computed, contextual information, so a simple field description or #field_suffix
just doesn't do it. I also want to keep the ability to move fields around in field UI. I'm trying to create a form_alter
hook to inject a render element with my docs right after that field.
I already have a working prototype:
function MYMODULE_form_ENITY_FORMMODE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$fieldToEnhance = 'field_foo';
if (!isset($form[$fieldToEnhance])) {
return;
}
$computedDocumentationVariables = mymodule_get_infos();
$renderElementToAppend[$fieldToEnhance . '_append'] = [
'#type' => 'inline_template',
'#template' => '<div>This is a very shortened and simplified placeholder.</div>',
'#context' => $computedDocumentationVariables,
'#parents' => $form[$fieldToEnhance]['#parents'] ?? [],
'#weight' => isset($form[$fieldToEnhance]['#weight']) ? $form[$fieldToEnhance]['#weight'] + 1 : NULL,
];
$positionOfField = array_search($fieldToEnhance, array_keys($form));
// inject the render element right after the field in the form array
$form = array_merge(
array_merge(
array_slice($form, 0, $positionOfField+1),
$renderElementToAppend
),
$form
);
}
This works as exptected for a very plain form.
But as soon as I move my field inside a container from Field group module, the positioning doesn't work as expected. When viewing it in a debugger, I can see that my custom render element is at the correct position inside the $form
array. But on screen it is not rendered at the correct position. (My documentation render element is on root level. I want it inside the container, right after the field.)
How do I make my hook aware of potential nesting containers from Field Group module?