Completed
Pull Request — 8.x-1.x (#126)
by Janez
02:06
created

WidgetsConfig::buildForm()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 89
Code Lines 65

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 4 Features 0
Metric Value
c 6
b 4
f 0
dl 0
loc 89
rs 8.38
cc 4
eloc 65
nc 8
nop 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * @file
5
 * Contains \Drupal\entity_browser\Form\WidgetsConfig.
6
 */
7
8
namespace Drupal\entity_browser\Form;
9
10
use Drupal\Core\Form\FormBase;
11
use Drupal\Core\Form\FormStateInterface;
12
use Drupal\entity_browser\WidgetManager;
13
use Symfony\Component\DependencyInjection\ContainerInterface;
14
15
/**
16
 * Widget configuration step in entity browser form wizard.
17
 */
18
class WidgetsConfig extends FormBase {
19
20
  /**
21
   * Entity browser widget plugin manager.
22
   *
23
   * @var \Drupal\entity_browser\WidgetManager
24
   */
25
  protected $widgetManager;
26
27
  /**
28
   * WidgetsConfig constructor.
29
   *
30
   * @param \Drupal\entity_browser\WidgetManager $widget_manager
31
   *   Entity browser widget plugin manager.
32
   */
33
  function __construct(WidgetManager $widget_manager) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
34
    $this->widgetManager = $widget_manager;
35
  }
36
37
  /**
38
   * {@inheritdoc}
39
   */
40
  public static function create(ContainerInterface $container) {
41
    return new static(
42
      $container->get('plugin.manager.entity_browser.widget')
43
    );
44
  }
45
46
  /**
47
   * {@inheritdoc}
48
   */
49
  public function getFormId() {
50
    return 'entity_browser_widgets_config_form';
51
  }
52
53
  /**
54
   * {@inheritdoc}
55
   */
56
  public function buildForm(array $form, FormStateInterface $form_state) {
57
    /** @var \Drupal\entity_browser\EntityBrowserInterface $entity_browser */
58
    $entity_browser = $form_state->getTemporaryValue('wizard')['entity_browser'];
59
60
    $widgets = [];
61
    foreach ($this->widgetManager->getDefinitions() as $plugin_id => $plugin_definition) {
62
      $widgets[$plugin_id] = $plugin_definition['label'];
63
    }
64
    $default_widgets = [];
65
    foreach ($entity_browser->getWidgets() as $widget) {
66
      /** @var \Drupal\entity_browser\WidgetInterface $widget */
67
      $default_widgets[] = $widget->id();
68
    }
69
    $form['widget'] = [
70
      '#type' => 'select',
71
      '#title' => $this->t('Add widget plugin'),
72
      '#options' => ['_none_' => '- ' . $this->t('Select a widget to add it') . ' -'] + $widgets,
73
      '#ajax' => [
74
        'callback' => [get_class($this), 'tableUpdatedAjaxCallback'],
75
        'wrapper' => 'widgets',
76
        'event' => 'change'
77
      ],
78
      '#executes_submit_callback' => TRUE,
79
      '#submit' => [[get_class($this), 'submitAddWidget']],
80
      '#limit_validation_errors' => [['widget']],
81
    ];
82
    $form_state->unsetValue('widget');
83
84
    $form['widgets'] = [
85
      '#type' => 'container',
86
      '#attributes' => ['id' => 'widgets'],
87
    ];
88
89
    $form['widgets']['table'] = [
90
      '#type' => 'table',
91
      '#header' => [
92
        $this->t('Form'),
93
        $this->t('Operations'),
94
        $this->t('Actions'),
95
        $this->t('Weight'),
96
      ],
97
      '#empty' => $this->t('There are no widgets.'),
98
      '#tabledrag' => [[
99
        'action' => 'order',
100
        'relationship' => 'sibling',
101
        'group' => 'variant-weight',
102
      ]],
103
    ];
104
105
    /** @var \Drupal\entity_browser\WidgetInterface $widget */
106
    foreach ($entity_browser->getWidgets() as $uuid => $widget) {
107
      $row = [
108
        '#attributes' => [
109
          'class' => ['draggable'],
110
        ],
111
      ];
112
      $row['label'] = [
113
        '#type' => 'textfield',
114
        '#default_value' => $widget->label(),
115
        '#title' => $this->t('Label'),
116
      ];
117
      $row['form'] = [];
118
      $row['form'] = $widget->buildConfigurationForm($row['form'], $form_state);
119
      $row['remove'] = [
120
        '#type' => 'submit',
121
        '#value' => $this->t('Delete'),
122
        '#name' => 'remove' . $uuid,
123
        '#ajax' => [
124
          'callback' => [get_class($this), 'tableUpdatedAjaxCallback'],
125
          'wrapper' => 'widgets',
126
          'event' => 'click'
127
        ],
128
        '#executes_submit_callback' => TRUE,
129
        '#submit' => [[get_class($this), 'submitDeleteWidget']],
130
        '#arguments' => $uuid,
131
      ];
132
      $row['weight'] = [
133
        '#type' => 'weight',
134
        '#default_value' => $widget->getWeight(),
135
        '#title' => $this->t('Weight for @widget widget', ['@widget' => $widget->label()]),
136
        '#title_display' => 'invisible',
137
        '#attributes' => [
138
          'class' => ['variant-weight'],
139
        ],
140
      ];
141
      $form['widgets']['table'][$uuid] = $row;
142
    }
143
    return $form;
144
  }
145
146
  /**
147
   * AJAX submit callback for adding widgets to the entity browser.
148
   */
149
  public static function submitAddWidget($form, FormStateInterface $form_state) {
150
    $cached_values = $form_state->getTemporaryValue('wizard');
151
    /** @var \Drupal\entity_browser\EntityBrowserInterface $entity_browser */
152
    $entity_browser = $cached_values['entity_browser'];
153
    $widgets_num = count($entity_browser->getWidgets());
154
    $widget = $form_state->getValue('widget');
155
    $weight = $widgets_num + 1;
156
    $entity_browser->addWidget([
157
      'id' => $widget,
158
      'label' => $widget,
159
      'weight' => $weight,
160
      // Configuration will be set on the widgets page.
161
      'settings' => [],
162
    ]);
163
    \Drupal::service('user.shared_tempstore')
164
      ->get('entity_browser.config')
165
      ->set($entity_browser->id(), $cached_values);
166
    $form_state->setRebuild();
167
  }
168
169
  /**
170
   * AJAX submit callback for removing widgets from the entity browser.
171
   */
172
  public static function submitDeleteWidget($form, FormStateInterface $form_state) {
173
    $cached_values = $form_state->getTemporaryValue('wizard');
174
    /** @var \Drupal\entity_browser\EntityBrowserInterface $entity_browser */
175
    $entity_browser = $cached_values['entity_browser'];
176
    $entity_browser->deleteWidget($entity_browser->getWidget($form_state->getTriggeringElement()['#arguments']));
177
    \Drupal::service('user.shared_tempstore')
178
      ->get('entity_browser.config')
179
      ->set($entity_browser->id(), $cached_values);
180
    $form_state->setRebuild();
181
  }
182
183
  /**
184
   * AJAX callback for all operations that update widgets table.
185
   */
186
  public static function tableUpdatedAjaxCallback($form, $form_state) {
187
    return $form['widgets'];
188
  }
189
190
  /**
191
   * {@inheritdoc}
192
   */
193
  public function validateForm(array &$form, FormStateInterface $form_state) {
194
    /** @var \Drupal\entity_browser\EntityBrowserInterface $entity_browser */
195
    $entity_browser = $form_state->getTemporaryValue('wizard')['entity_browser'];
196
    /** @var \Drupal\entity_browser\WidgetInterface $widget */
197
    foreach ($entity_browser->getWidgets() as $widget) {
198
      $widget->validateConfigurationForm($form, $form_state);
199
    }
200
  }
201
202
  /**
203
   * {@inheritdoc}
204
   */
205
  public function submitForm(array &$form, FormStateInterface $form_state) {
206
    /** @var \Drupal\entity_browser\EntityBrowserInterface $entity_browser */
207
    $entity_browser = $form_state->getTemporaryValue('wizard')['entity_browser'];
208
    $table = $form_state->getValue('table');
209
    /** @var \Drupal\entity_browser\WidgetInterface $widget */
210
    foreach ($entity_browser->getWidgets() as $uuid => $widget) {
211
      $widget->submitConfigurationForm($form, $form_state);
212
      $widget->setConfiguration([
213
        'settings' => !empty($table[$uuid]['form']) ? $table[$uuid]['form'] : [],
214
        'weight' => $table[$uuid]['weight'],
215
        'label' => $table[$uuid]['label'],
216
        'uuid' => $uuid,
217
        'id' => $widget->id(),
218
      ]);
219
    }
220
  }
221
222
}
223