Skip to content

Instantly share code, notes, and snippets.

@msankhala
Forked from leymannx/Drupal8HorizontalTabs.php
Created December 14, 2023 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msankhala/255ea2580d3e5a393ddef14179ad26be to your computer and use it in GitHub Desktop.
Save msankhala/255ea2580d3e5a393ddef14179ad26be to your computer and use it in GitHub Desktop.
How to create horizontal tabs programmatically in Drupal 8, requires Field Group module
<?php
// How to create horizontal tabs programmatically in Drupal 8, requires Field Group module
$form = array();
$form['my_field'] = array(
'#type' => 'horizontal_tabs',
'#tree' => TRUE,
'#prefix' => '<div id="unique-wrapper">',
'#suffix' => '</div>',
);
$items = array(
array(
'nid' => 1,
'name' => 'Item 1'
),
array(
'nid' => 2,
'name' => 'Item 2'
),
array(
'nid' => 3,
'name' => 'Item 3'
),
array(
'nid' => 4,
'name' => 'Item 4'
),
);
$counter = 1;
foreach ($items as $item) {
$nid = $item['nid'];
$form['my_field']['stuff'][$nid] = array(
'#type' => 'details',
'#title' => t('Item @no', array('@no' => $counter)),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['my_field']['stuff'][$nid]['form']['item_id'] = array(
'#type' => 'value',
'#value' => $item['nid'],
);
$form['my_field']['stuff'][$nid]['form']['item_name'] = array(
'#type' => 'value',
'#value' => $item['name'],
);
$form['my_field']['stuff'][$nid]['form']['remove'] = array(
'#type' => 'checkbox',
'#title' => t('Remove this item'),
'#weight' => -51,
);
// more field definition
$form['my_field']['stuff'][$nid]['form']['#tree'] = TRUE;
$form['my_field']['stuff'][$nid]['form']['#parents'] = array('my_field', 'stuff', $nid, 'form');
$counter++;
}
// under certain circumstances you have to attach the horizontal tabs library manually
$form['#attached']['library'][] = 'field_group/formatter.horizontal_tabs';
return $form;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment