Completed
Push — 8.x-1.x ( b8d656...2e59f4 )
by Janez
02:49
created

EntityForm::updateBundle()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
3
namespace Drupal\entity_browser_entity_form\Plugin\EntityBrowser\Widget;
4
5
use Drupal\Core\Ajax\AjaxResponse;
6
use Drupal\Core\Ajax\ReplaceCommand;
7
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
8
use Drupal\Core\Entity\EntityTypeInterface;
9
use Drupal\Core\Entity\EntityTypeManagerInterface;
10
use Drupal\Core\Form\FormStateInterface;
11
use Drupal\entity_browser\WidgetBase;
12
use Drupal\entity_browser\WidgetValidationManager;
13
use Symfony\Component\DependencyInjection\ContainerInterface;
14
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
15
use Drupal\Core\Entity\EntityDisplayRepositoryInterface;
16
17
/**
18
 * Uses a view to provide entity listing in a browser's widget.
19
 *
20
 * @EntityBrowserWidget(
21
 *   id = "entity_form",
22
 *   label = @Translation("Entity form"),
23
 *   description = @Translation("Provides entity form widget.")
24
 * )
25
 */
26
class EntityForm extends WidgetBase {
27
28
  /**
29
   * The entity type bundle info service.
30
   *
31
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
32
   */
33
  protected $entityTypeBundleInfo;
34
35
  /**
36
   * The entity display repository.
37
   *
38
   * @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface
39
   */
40
  protected $entityDisplayRepository;
41
42
  /**
43
   * Constructs widget plugin.
44
   *
45
   * @param array $configuration
46
   *   A configuration array containing information about the plugin instance.
47
   * @param string $plugin_id
48
   *   The plugin_id for the plugin instance.
49
   * @param mixed $plugin_definition
50
   *   The plugin implementation definition.
51
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
52
   *   Event dispatcher service.
53
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
54
   *   The entity type manager service.
55
   * @param \Drupal\entity_browser\WidgetValidationManager $validation_manager
56
   *   The Widget Validation Manager service.
57
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
58
   *   The entity type bundle info service.
59
   * @param \Drupal\Core\Entity\EntityDisplayRepositoryInterface $entity_display_repository
60
   *   The entity display repository.
61
   */
62
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EventDispatcherInterface $event_dispatcher, EntityTypeManagerInterface $entity_type_manager, WidgetValidationManager $validation_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info, EntityDisplayRepositoryInterface $entity_display_repository) {
63
    parent::__construct($configuration, $plugin_id, $plugin_definition, $event_dispatcher, $entity_type_manager, $validation_manager);
64
    $this->entityTypeBundleInfo = $entity_type_bundle_info;
65
    $this->entityDisplayRepository = $entity_display_repository;
66
  }
67
68
  /**
69
   * {@inheritdoc}
70
   */
71 View Code Duplication
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
72
    return new static(
73
      $configuration,
74
      $plugin_id,
75
      $plugin_definition,
76
      $container->get('event_dispatcher'),
77
      $container->get('entity_type.manager'),
78
      $container->get('plugin.manager.entity_browser.widget_validation'),
79
      $container->get('entity_type.bundle.info'),
80
      $container->get('entity_display.repository')
81
    );
82
  }
83
84
  /**
85
   * {@inheritdoc}
86
   */
87
  public function defaultConfiguration() {
88
    return [
89
      'entity_type' => NULL,
90
      'bundle' => NULL,
91
      'form_mode' => 'default',
92
    ] + parent::defaultConfiguration();
93
  }
94
95
  /**
96
   * {@inheritdoc}
97
   */
98
  public function getForm(array &$original_form, FormStateInterface $form_state, array $aditional_widget_parameters) {
99
    if (empty($this->configuration['entity_type']) || empty($this->configuration['bundle'])  || empty($this->configuration['form_mode'])) {
100
      return ['#markup' => t('The settings for this widget (Entity type, Bundle or Form mode) are not configured correctly.')];
101
    }
102
103
    return [
104
      'inline_entity_form' => [
105
        '#type' => 'inline_entity_form',
106
        '#op' => 'add',
107
        '#entity_type' => $this->configuration['entity_type'],
108
        '#bundle' => $this->configuration['bundle'],
109
        '#form_mode' => $this->configuration['form_mode'],
110
      ],
111
    ];
112
  }
113
114
  /**
115
   * {@inheritdoc}
116
   */
117
  protected function prepareEntities(array $form, FormStateInterface $form_state) {
118
    return [$form[$form['#browser_parts']['widget']]['inline_entity_form']['#entity']];
119
  }
120
121
  /**
122
   * {@inheritdoc}
123
   */
124
  public function submit(array &$element, array &$form, FormStateInterface $form_state) {
125
    $this->selectEntities($this->prepareEntities($form, $form_state), $form_state);
126
  }
127
128
  /**
129
   * {@inheritdoc}
130
   */
131
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
132
    $parents = ['table', $this->uuid(), 'form'];
133
    $entity_type = $form_state->hasValue(array_merge($parents, ['entity_type'])) ? $form_state->getValue(array_merge($parents, ['entity_type'])) : $this->configuration['entity_type'];
134
    $bundle = $form_state->hasValue(array_merge($parents, ['bundle', 'select'])) ? $form_state->getValue(array_merge($parents, ['bundle', 'select'])) : $this->configuration['bundle'];
135
    $form_mode = $form_state->hasValue(array_merge($parents, ['form_mode', 'form_select'])) ? $form_state->hasValue(array_merge($parents, ['form_mode', 'form_select'])) : $this->configuration['form_mode'];
136
137
    $definitions = $this->entityTypeManager->getDefinitions();
138
    $entity_types = array_combine(
139
      array_keys($definitions),
140
      array_map(function (EntityTypeInterface $item) {
141
        return $item->getLabel();
142
      }, $definitions)
143
    );
144
145
    $form['entity_type'] = [
146
      '#type' => 'select',
147
      '#title' => $this->t('Entity type'),
148
      '#options' => $entity_types,
149
      '#default_value' => $entity_type,
150
      '#ajax' => [
151
        'callback' => [$this, 'updateFormElements'],
152
      ],
153
    ];
154
155
    $bundles = [];
156
    if ($entity_type) {
157
      $definitions = $this->entityTypeBundleInfo->getBundleInfo($entity_type);
158
      $bundles = array_map(function ($item) {
159
        return $item['label'];
160
      }, $definitions);
161
    }
162
163
    $form['bundle'] = [
164
      '#type' => 'container',
165
      'select' => [
166
        '#type' => 'select',
167
        '#title' => $this->t('Bundle'),
168
        '#options' => $bundles,
169
        '#default_value' => $bundle,
170
      ],
171
      '#attributes' => ['id' => 'bundle-wrapper-' . $this->uuid()],
172
    ];
173
174
    $form['form_mode'] = [
175
      '#type' => 'container',
176
      'form_select' => [
177
        '#type' => 'select',
178
        '#title' => $this->t('Form mode'),
179
        '#default_value' => $form_mode,
180
        '#options' => $this->entityDisplayRepository->getFormModeOptions($entity_type),
181
      ],
182
      '#attributes' => ['id' => 'form-mode-wrapper-' . $this->uuid()],
183
    ];
184
185
    return $form;
186
  }
187
188
  /**
189
   * AJAX callback for bundle dropdown update.
190
   */
191
  public function updateBundle($form, FormStateInterface $form_state) {
192
    return $form['widgets']['table'][$this->uuid()]['form']['bundle'];
193
  }
194
195
  /**
196
   * AJAX callback for the Form Mode dropdown update.
197
   */
198
  public function updateFormMode($form, FormStateInterface $form_state) {
199
    return $form['widgets']['table'][$this->uuid()]['form']['form_mode'];
200
  }
201
202
  /**
203
   * AJAX callback to update the two form elements: bundle and form_mode.
204
   */
205
  public function updateFormElements($form, FormStateInterface $form_state) {
206
    $response = new AjaxResponse();
207
    $response->addCommand(new ReplaceCommand('#bundle-wrapper-' . $this->uuid(), $this->updateBundle($form, $form_state)));
208
    $response->addCommand(new ReplaceCommand('#form-mode-wrapper-' . $this->uuid(), $this->updateFormMode($form, $form_state)));
209
    return $response;
210
  }
211
212
  /**
213
   * {@inheritdoc}
214
   */
215
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
216
    parent::submitConfigurationForm($form, $form_state);
217
    $this->configuration['bundle'] = $this->configuration['bundle']['select'];
218
    $this->configuration['form_mode'] = $this->configuration['form_mode']['form_select'];
219
  }
220
221
}
222