Completed
Push — 8.x-1.x ( 6b2210...a384d8 )
by Dave
8s
created

EmbedButtonForm::validateForm()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 1
Metric Value
c 6
b 0
f 1
dl 0
loc 19
rs 9.2
cc 4
eloc 11
nc 3
nop 2
1
<?php
2
3
/**
4
 * @file
5
 * Contains \Drupal\embed\Form\EmbedButtonForm.
6
 */
7
8
namespace Drupal\embed\Form;
9
10
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
11
use Drupal\Core\Ajax\AjaxResponse;
12
use Drupal\Core\Ajax\ReplaceCommand;
13
use Drupal\Core\Config\ConfigFactoryInterface;
14
use Drupal\Core\Entity\EntityForm;
15
use Drupal\Core\Entity\EntityTypeManagerInterface;
16
use Drupal\Core\Entity\EntityTypeInterface;
17
use Drupal\Core\Form\FormStateInterface;
18
use Drupal\embed\EmbedType\EmbedTypeManager;
19
use Symfony\Component\DependencyInjection\ContainerInterface;
20
21
/**
22
 * Form controller for embed button forms.
23
 */
24
class EmbedButtonForm extends EntityForm {
25
26
  /**
27
   * The entity type manager service.
28
   *
29
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
30
   */
31
  protected $entityTypeManager;
32
33
  /**
34
   * The embed type plugin manager.
35
   *
36
   * @var \Drupal\embed\EmbedType\EmbedTypeManager
37
   */
38
  protected $embedTypeManager;
39
40
  /**
41
   * Constructs a new EmbedButtonForm.
42
   *
43
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
44
   *   The entity type manager service.
45
   * @param \Drupal\embed\EmbedType\EmbedTypeManager $embed_type_manager
46
   *   The embed type plugin manager.
47
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
48
   *   The config factory.
49
   */
50
  public function __construct(EntityTypeManagerInterface $entity_type_manager, EmbedTypeManager $embed_type_manager, ConfigFactoryInterface $config_factory) {
51
    $this->entityTypeManager = $entity_type_manager;
52
    $this->embedTypeManager = $embed_type_manager;
53
    $this->configFactory = $config_factory;
54
  }
55
56
  /**
57
   * {@inheritdoc}
58
   */
59
  public static function create(ContainerInterface $container) {
60
    return new static(
61
      $container->get('entity_type.manager'),
62
      $container->get('plugin.manager.embed.type'),
63
      $container->get('config.factory')
64
    );
65
  }
66
67
  /**
68
   * {@inheritdoc}
69
   */
70
  public function form(array $form, FormStateInterface $form_state) {
71
    $form = parent::form($form, $form_state);
72
73
    /** @var \Drupal\embed\EmbedButtonInterface $button */
74
    $button = $this->entity;
75
    $form_state->setTemporaryValue('embed_button', $button);
76
77
    $form['label'] = [
78
      '#title' => $this->t('Label'),
79
      '#type' => 'textfield',
80
      '#default_value' => $button->label(),
81
      '#description' => t('The human-readable name of this embed button. This text will be displayed when the user hovers over the CKEditor button. This name must be unique.'),
82
      '#required' => TRUE,
83
      '#size' => 30,
84
    ];
85
86
    $form['id'] = [
87
      '#type' => 'machine_name',
88
      '#default_value' => $button->id(),
89
      '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
90
      '#disabled' => !$button->isNew(),
91
      '#machine_name' => [
92
        'exists' => ['Drupal\embed\Entity\EmbedButton', 'load'],
93
      ],
94
      '#description' => $this->t('A unique machine-readable name for this embed button. It must only contain lowercase letters, numbers, and underscores.'),
95
    ];
96
97
    $form['type_id'] = [
98
      '#type' => 'select',
99
      '#title' => $this->t('Embed type'),
100
      '#options' => $this->embedTypeManager->getDefinitionOptions(),
101
      '#default_value' => $button->getTypeId(),
102
      '#required' => TRUE,
103
      '#ajax' => [
104
        'callback' => '::updateTypeSettings',
105
        'effect' => 'fade',
106
      ],
107
      '#disabled' => !$button->isNew(),
108
    ];
109
    if (count($form['type_id']['#options']) == 0) {
110
      drupal_set_message($this->t('No embed types found.'), 'warning');
111
    }
112
113
    // Add the embed type plugin settings.
114
    $form['type_settings'] = [
115
      '#type' => 'container',
116
      '#tree' => TRUE,
117
      '#prefix' => '<div id="embed-type-settings-wrapper">',
118
      '#suffix' => '</div>',
119
    ];
120
121
    try {
122
      if ($plugin = $button->getTypePlugin()) {
123
        $form['type_settings'] = $plugin->buildConfigurationForm($form['type_settings'], $form_state);
124
      }
125
    }
126
    catch (PluginNotFoundException $exception) {
0 ignored issues
show
Bug introduced by
The class Drupal\Component\Plugin\...PluginNotFoundException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
127
      drupal_set_message($exception->getMessage(), 'error');
128
      watchdog_exception('embed', $exception);
129
      $form['type_id']['#disabled'] = FALSE;
130
    }
131
132
    $config = $this->config('embed.settings');
133
    $upload_location = $config->get('file_scheme') . '://' . $config->get('upload_directory') . '/';
134
    $form['icon_file'] = [
135
      '#title' => $this->t('Button icon'),
136
      '#type' => 'managed_file',
137
      '#description' => $this->t('Icon for the button to be shown in CKEditor toolbar. Leave empty to use the default Entity icon.'),
138
      '#upload_location' => $upload_location,
139
      '#upload_validators' => [
140
        'file_validate_extensions' => ['gif png jpg jpeg'],
141
        'file_validate_image_resolution' => ['32x32', '16x16'],
142
      ],
143
    ];
144
    if ($file = $button->getIconFile()) {
145
      $form['icon_file']['#default_value'] = ['target_id' => $file->id()];
146
    }
147
148
    return $form;
149
  }
150
151
  /**
152
   * {@inheritdoc}
153
   */
154
  public function validateForm(array &$form, FormStateInterface $form_state) {
155
    parent::validateForm($form, $form_state);
156
157
    /** @var \Drupal\embed\EmbedButtonInterface $button */
158
    $button = $this->entity;
159
160
    // Run embed type plugin validation.
161
    if ($plugin = $button->getTypePlugin()) {
162
      $plugin_form_state = clone $form_state;
163
      $plugin_form_state->setValues($button->getTypeSettings());
164
      $plugin->validateConfigurationForm($form['type_settings'], $plugin_form_state);
165
      if ($errors = $plugin_form_state->getErrors()) {
166
        foreach ($errors as $name => $error) {
167
          $form_state->setErrorByName($name, $error);
168
        }
169
      }
170
      $form_state->setValue('type_settings', $plugin_form_state->getValues());
171
    }
172
  }
173
174
  /**
175
   * {@inheritdoc}
176
   */
177
  public function save(array $form, FormStateInterface $form_state) {
178
    /** @var \Drupal\embed\EmbedButtonInterface $button */
179
    $button = $this->entity;
180
181
    // Run embed type plugin submission.
182
    $plugin = $button->getTypePlugin();
183
    $plugin_form_state = clone $form_state;
184
    $plugin_form_state->setValues($button->getTypeSettings());
185
    $plugin->submitConfigurationForm($form['type_settings'], $plugin_form_state);
186
    $form_state->setValue('type_settings', $plugin->getConfiguration());
187
    $button->set('type_settings', $plugin->getConfiguration());
188
189
    $icon_fid = $form_state->getValue(['icon_file', '0']);
190
    // If a file was uploaded to be used as the icon, get its UUID to be stored
191
    // in the config entity.
192
    if (!empty($icon_fid) && $file = $this->entityTypeManager->getStorage('file')->load($icon_fid)) {
193
      $button->set('icon_uuid', $file->uuid());
194
    }
195
    else {
196
      $button->set('icon_uuid', NULL);
197
    }
198
199
    $status = $button->save();
200
201
    $t_args = ['%label' => $button->label()];
202
203
    if ($status == SAVED_UPDATED) {
204
      drupal_set_message($this->t('The embed button %label has been updated.', $t_args));
205
    }
206
    elseif ($status == SAVED_NEW) {
207
      drupal_set_message($this->t('The embed button %label has been added.', $t_args));
208
      $context = array_merge($t_args, ['link' => $button->link($this->t('View'), 'collection')]);
209
      $this->logger('embed')->notice('Added embed button %label.', $context);
210
    }
211
212
    $form_state->setRedirectUrl($button->urlInfo('collection'));
213
  }
214
215
  /**
216
   * Ajax callback to update the form fields which depend on embed type.
217
   *
218
   * @param array $form
219
   *   The build form.
220
   * @param \Drupal\Core\Form\FormStateInterface $form_state
221
   *   The form state.
222
   *
223
   * @return \Drupal\Core\Ajax\AjaxResponse
224
   *   Ajax response with updated options for the embed type.
225
   */
226
  public function updateTypeSettings(array &$form, FormStateInterface $form_state) {
227
    $response = new AjaxResponse();
228
229
    // Update options for entity type bundles.
230
    $response->addCommand(new ReplaceCommand(
231
      '#embed-type-settings-wrapper',
232
      $form['type_settings']
233
    ));
234
235
    return $response;
236
  }
237
}
238