Forked from mecmartini/drupal-and-react-field-formatter.php
Created
April 20, 2022 21:33
-
-
Save jcicero518/4832326ca48b337601fd50686eb1e9c0 to your computer and use it in GitHub Desktop.
Drupal and React - Field Formatter
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
/** | |
* {@inheritdoc} | |
*/ | |
public function viewElements(FieldItemListInterface $items, $langcode) { | |
$elements = []; | |
$id = $items->getEntity()->id(); | |
# Generate a wrapper to use as dom root to attach the React component. | |
$field_name = $this->fieldDefinition->getItemDefinition()->getFieldDefinition()->getName(); | |
$wrapper_id = 'drupal-and-react-app-' . $field_name .'-'. $id; | |
$build = [ | |
'#markup' => '<div id="' . $wrapper_id . '"></div>', | |
]; | |
# Get field items and values. | |
foreach ($items as $delta => $item) { | |
$elements[$delta] = $item->value; | |
} | |
# Attach the React component to the field formatter. | |
$build['#attached']['library'] = [ | |
'drupal_and_react/app_bundle', | |
]; | |
# Send the required data to the React component via Drupal settings. | |
$build['#attached']['drupalSettings']['drupal_and_react_app'][$id] = [ | |
'id' => $id, | |
'wrapper' => $wrapper_id, | |
'content' => $elements, | |
]; | |
return $build; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment