|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Drupal\quanthub_visualization\Plugin\Field\FieldWidget; |
| 4 | + |
| 5 | +use Drupal\Core\Field\FieldItemListInterface; |
| 6 | +use Drupal\Core\Field\WidgetBase; |
| 7 | +use Drupal\Core\Form\FormStateInterface; |
| 8 | +use Drupal\multivalue_form_element\Element\MultiValue; |
| 9 | + |
| 10 | +/** |
| 11 | + * Implementation of the 'quanthub_visualization_transformation_json' widget. |
| 12 | + * |
| 13 | + * @todo refactor and remove. |
| 14 | + * |
| 15 | + * @FieldWidget( |
| 16 | + * id = "quanthub_visualization_transformation_json", |
| 17 | + * label = @Translation("Quanthub Visualization Data Transformation Widget"), |
| 18 | + * field_types = { |
| 19 | + * "json", |
| 20 | + * "json_native", |
| 21 | + * "json_native_binary" |
| 22 | + * } |
| 23 | + * ) |
| 24 | + */ |
| 25 | +class QuanthubVisualizationTransformationWidget extends WidgetBase { |
| 26 | + |
| 27 | + /** |
| 28 | + * {@inheritdoc} |
| 29 | + */ |
| 30 | + public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { |
| 31 | + $json_value = json_decode($items->getString(), 1); |
| 32 | + |
| 33 | + // @todo add remove button. |
| 34 | + $element['value'] = [ |
| 35 | + '#type' => 'multivalue', |
| 36 | + '#title' => $this->t('Data Transformation Config'), |
| 37 | + '#cardinality' => MultiValue::CARDINALITY_UNLIMITED, |
| 38 | + '#default_value' => !empty($json_value['display']) ? $json_value['display'] : [], |
| 39 | + 'dimensionId' => [ |
| 40 | + '#type' => 'textfield', |
| 41 | + '#title' => $this->t('Dimension ID'), |
| 42 | + ], |
| 43 | + 'field' => [ |
| 44 | + '#type' => 'textfield', |
| 45 | + '#title' => $this->t('Field'), |
| 46 | + ], |
| 47 | + '#element_validate' => [ |
| 48 | + [$this, 'validate'], |
| 49 | + ], |
| 50 | + ]; |
| 51 | + |
| 52 | + return $element; |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Validation and setting value in widget. |
| 57 | + * |
| 58 | + * @param array $element |
| 59 | + * The render array of element. |
| 60 | + * @param \Drupal\Core\Form\FormStateInterface $form_state |
| 61 | + * The form_state object. |
| 62 | + */ |
| 63 | + public function validate($element, FormStateInterface $form_state) { |
| 64 | + $value = $element['#value']; |
| 65 | + |
| 66 | + $value = array_filter($value, function ($item) { |
| 67 | + if (empty($item['dimensionId']) && empty($item['field'])) { |
| 68 | + return FALSE; |
| 69 | + } |
| 70 | + else { |
| 71 | + return TRUE; |
| 72 | + } |
| 73 | + }); |
| 74 | + |
| 75 | + $value = json_encode(['display' => $value]); |
| 76 | + $form_state->setValueForElement($element, $value); |
| 77 | + } |
| 78 | + |
| 79 | +} |
0 commit comments