3 namespace Drupal\metatag\Plugin\Field\FieldWidget;
5 use Drupal\Core\Field\FieldItemListInterface;
6 use Drupal\Core\Field\WidgetBase;
7 use Drupal\Core\Form\FormStateInterface;
8 use Drupal\Core\Field\FieldDefinitionInterface;
9 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
10 use Drupal\metatag\MetatagManager;
11 use Symfony\Component\DependencyInjection\ContainerInterface;
14 * Advanced widget for metatag field.
17 * id = "metatag_firehose",
18 * label = @Translation("Advanced meta tags form"),
24 class MetatagFirehose extends WidgetBase implements ContainerFactoryPluginInterface {
27 * Instance of MetatagManager service.
29 protected $metatagManager;
34 public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
38 $configuration['field_definition'],
39 $configuration['settings'],
40 $configuration['third_party_settings'],
41 $container->get('metatag.manager')
48 public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, MetatagManager $manager) {
49 parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
50 $this->metatagManager = $manager;
56 public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
57 $item = $items[$delta];
58 $default_tags = metatag_get_default_tags();
60 // Retrieve the values for each metatag from the serialized array.
62 if (!empty($item->value)) {
63 $values = unserialize($item->value);
66 // Populate fields which have not been overridden in the entity.
67 if (!empty($default_tags)) {
68 foreach ($default_tags as $tag_id => $tag_value) {
69 if (!isset($values[$tag_id]) && !empty($tag_value)) {
70 $values[$tag_id] = $tag_value;
75 // Create the form element.
76 $element = $this->metatagManager->form($values, $element, [$item->getEntity()->getentityTypeId()]);
78 // Put the form element into the form's "advanced" group.
79 $element['#group'] = 'advanced';
87 public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
88 // Flatten the values array to remove the groups and then serialize all the
89 // metatags into one value for storage.
90 $tag_manager = \Drupal::service('plugin.manager.metatag.tag');
91 $tags = $tag_manager->getDefinitions();
92 foreach ($values as &$value) {
93 $flattened_value = [];
94 foreach ($value as $group) {
95 // Exclude the "original delta" value.
96 if (is_array($group)) {
97 foreach ($group as $tag_id => $tag_value) {
98 $tag = $tag_manager->createInstance($tag_id);
99 $tag->setValue($tag_value);
100 if (!empty($tag->value())) {
101 $flattened_value[$tag_id] = $tag->value();
106 $value = serialize($flattened_value);