Altering a Drupal Field Group field.

Field group module and its hooks

Pasan Gamage
3 min readApr 25, 2024

If you are using field groups, you are probably aware of the ‘Add field group’ button under manage form display. This comes from the contrib module called Field Groups https://www.drupal.org/project/field_group

This module lets us organise our forms in a clean and tidy way for the end user.

For this example, I’ve created two Fieldset type field groups and organised the fields under them.

This will display on the Front end as follows,

Now let’s see how to add a prefix text wrapped in a div tag in to the About me field group, right before other fields. And also a suffix text wrapped in a div tag at the end of the contact details field group before the last field, which is contact settings.

The Code

For this task, we can check the field group API in web/modules/contrib/field_group/field_group.api.php

And if we take a look at the hook_field_group_form_process_alter() hook, it seems like the right one to tap into, to alter the form API.

All you need is a custom module and in your custom module’s .module file, add the below function. The custom module I’m using playground_form

/**
* Implements hook_field_group_form_process_alter().
*/
function playground_form_field_group_form_process_alter(array &$element, &$group, &$complete_form) {
if ($group->group_name === 'group_about_me') {
$element['#field_prefix'] = [
'#type' => 'html_tag',
'#tag' => 'div',
'#value' => t('Please share a bit about you.'),
'#attributes' => [
'id' => 'about_me_group_prefix',
],
];
}
if ($group->group_name === 'group_contact_details') {
$element['#field_suffix'] = [
'#type' => 'html_tag',
'#tag' => 'div',
'#value' => t('Don\'t worry, we won\'t subscribe you to our mailing list.'),
'#attributes' => [
'id' => 'contact_group_prefix',
],
];
}
}

We need to make sure we are adding the prefix and the suffix text to the right field groups, hence we check it using $group->group_name

#tag We can use field type of html_tag and because we want it to be wrapped in div tags we use the tag property.

#value is simply a string that needs to be rendered TranslatableMarkup type hence the t()

#attributes now for this you can provide any additional CSS attribute such as class, width, height etc.

Final Result

The rendered output will look like this;

--

--

Pasan Gamage
Pasan Gamage

Written by Pasan Gamage

Backend Developer | Motorbike enthusiast

No responses yet