Last active
August 4, 2022 11:57
-
-
Save BBGuy/6a0cae77aaf8a43fff67434167f2c976 to your computer and use it in GitHub Desktop.
Drupal 9 - Field Group integration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Field group does not by default show on commerce relaed entities and those can be added using a hook | |
/** | |
* Implements hook_field_group_content_element_keys_alter | |
* | |
* Add field groups to product and product variation. | |
*/ | |
function fcl_commerce_field_group_content_element_keys_alter(&$keys) { | |
if (!isset($keys['commerce_product_variation'])) { | |
$keys['commerce_product_variation'] = 'product_variation'; | |
} | |
if (!isset($keys['commerce_product'])) { | |
$keys['commerce_product'] = 'product'; | |
} | |
} | |
// Commerce products do not show the field group but we can programmatically get those details | |
/** | |
* Implements template_preprocess_commerce_product(). | |
*/ | |
function mytheme_preprocess_commerce_product(&$variables) { | |
$product = $variables['elements']['#commerce_product']; | |
$productvars = $variables['product']; | |
if (is_object($product)) { | |
$view_mode = $variables['elements']['#view_mode']; | |
if ($view_mode == 'full') { | |
$variables['field_group_fields'] = _getFieldGroupFields($variables); | |
} | |
} | |
/* | |
* Get the field group fields from the field group | |
*/ | |
function _getFieldGroupFields(&$variables) { | |
$techspecfields = []; | |
// Get the list of fields from the product variation using EntityViewDisplay | |
$variation =_getProductVariation($variables); | |
if (!empty($variation)) { | |
$display_options = EntityViewDisplay::collectRenderDisplay($variation, 'full'); | |
$field_group = $display_options->getThirdPartySetting('field_group', 'fieldgroup_one'); | |
foreach ($field_group['children'] as $item) { | |
$fld = $variation->{$item}; | |
/** @var \Drupal\field\Entity\FieldConfig $fld_def */ | |
$fld_def = $fld->getFieldDefinition(); | |
$lbl = $fld_def->getLabel(); | |
$fieldgroup_one[$item] = $lbl; | |
} | |
} | |
// Code for illustration only - should do more processing of the array to make it usable by the Twig template. | |
retuen $fieldgroup_one | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment