06cbbdc0b809560d7f52ac55dbeba826eab327c3
[yaffs-website] / Form / EntityInlineForm.php
1 <?php
2
3 namespace Drupal\inline_entity_form\Form;
4
5 use Drupal\Core\Entity\ContentEntityInterface;
6 use Drupal\Core\Entity\Entity\EntityFormDisplay;
7 use Drupal\Core\Entity\EntityInterface;
8 use Drupal\Core\Entity\EntityFieldManagerInterface;
9 use Drupal\Core\Entity\EntityTypeInterface;
10 use Drupal\Core\Entity\EntityTypeManagerInterface;
11 use Drupal\Core\Extension\ModuleHandlerInterface;
12 use Drupal\Core\Field\WidgetBase;
13 use Drupal\Core\Form\FormStateInterface;
14 use Drupal\Core\Render\Element;
15 use Drupal\inline_entity_form\InlineFormInterface;
16 use Symfony\Component\DependencyInjection\ContainerInterface;
17
18 /**
19  * Generic entity inline form handler.
20  */
21 class EntityInlineForm implements InlineFormInterface {
22
23   /**
24    * The entity field manager.
25    *
26    * @var \Drupal\Core\Entity\EntityFieldManagerInterface
27    */
28   protected $entityFieldManager;
29
30   /**
31    * The entity type manager.
32    *
33    * @var \Drupal\Core\Entity\EntityTypeManagerInterface
34    */
35   protected $entityTypeManager;
36
37   /**
38    * The entity type managed by this handler.
39    *
40    * @var \Drupal\Core\Entity\EntityTypeInterface
41    */
42   protected $entityType;
43
44   /**
45    * Module handler service.
46    *
47    * @var \Drupal\Core\Extension\ModuleHandlerInterface
48    */
49   protected $moduleHandler;
50
51   /**
52    * Constructs the inline entity form controller.
53    *
54    * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
55    *   The entity field manager.
56    * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
57    *   The entity type manager.
58    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
59    *   The module handler.
60    * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
61    *   The entity type.
62    */
63   public function __construct(EntityFieldManagerInterface $entity_field_manager, EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, EntityTypeInterface $entity_type) {
64     $this->entityFieldManager = $entity_field_manager;
65     $this->entityTypeManager = $entity_type_manager;
66     $this->moduleHandler = $module_handler;
67     $this->entityType = $entity_type;
68   }
69
70   /**
71    * {@inheritdoc}
72    */
73   public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
74     return new static(
75       $container->get('entity_field.manager'),
76       $container->get('entity_type.manager'),
77       $container->get('module_handler'),
78       $entity_type
79     );
80   }
81
82   /**
83    * {@inheritdoc}
84    */
85   public function getEntityType() {
86     return $this->entityType;
87   }
88
89   /**
90    * {@inheritdoc}
91    */
92   public function getEntityTypeLabels() {
93     $lowercase_label = $this->entityType->getLowercaseLabel();
94     return [
95       'singular' => $lowercase_label,
96       'plural' => t('@entity_type entities', ['@entity_type' => $lowercase_label]),
97     ];
98   }
99
100   /**
101    * {@inheritdoc}
102    */
103   public function getEntityLabel(EntityInterface $entity) {
104     return $entity->label();
105   }
106
107   /**
108    * {@inheritdoc}
109    */
110   public function getTableFields($bundles) {
111     $definitions = $this->entityFieldManager->getBaseFieldDefinitions($this->entityType->id());
112     $label_key = $this->entityType->getKey('label');
113     $label_field_label = t('Label');
114     if ($label_key && isset($definitions[$label_key])) {
115       $label_field_label = $definitions[$label_key]->getLabel();
116     }
117     $bundle_key = $this->entityType->getKey('bundle');
118     $bundle_field_label = t('Type');
119     if ($bundle_key && isset($definitions[$bundle_key])) {
120       $bundle_field_label = $definitions[$bundle_key]->getLabel();
121     }
122
123     $fields = [];
124     $fields['label'] = [
125       'type' => 'label',
126       'label' => $label_field_label,
127       'weight' => 1,
128     ];
129     if (count($bundles) > 1) {
130       $fields[$bundle_key] = [
131         'type' => 'field',
132         'label' => $bundle_field_label,
133         'weight' => 2,
134         'display_options' => [
135           'type' => 'entity_reference_label',
136           'settings' => ['link' => FALSE],
137         ],
138       ];
139     }
140
141     return $fields;
142   }
143
144   /**
145    * {@inheritdoc}
146    */
147   public function isTableDragEnabled($element) {
148     $children = Element::children($element);
149     // If there is only one row, disable tabledrag.
150     if (count($children) == 1) {
151       return FALSE;
152     }
153     // If one of the rows is in form context, disable tabledrag.
154     foreach ($children as $key) {
155       if (!empty($element[$key]['form'])) {
156         return FALSE;
157       }
158     }
159
160     return TRUE;
161   }
162
163   /**
164    * {@inheritdoc}
165    */
166   public function entityForm(array $entity_form, FormStateInterface $form_state) {
167     /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
168     $entity = $entity_form['#entity'];
169     $form_display = $this->getFormDisplay($entity, $entity_form['#form_mode']);
170     $form_display->buildForm($entity, $entity_form, $form_state);
171     $entity_form['#ief_element_submit'][] = [get_class($this), 'submitCleanFormState'];
172     // Inline entities inherit the parent language.
173     $langcode_key = $this->entityType->getKey('langcode');
174     if ($langcode_key && isset($entity_form[$langcode_key])) {
175       $entity_form[$langcode_key]['#access'] = FALSE;
176     }
177     if (!empty($entity_form['#translating'])) {
178       // Hide the non-translatable fields.
179       foreach ($entity->getFieldDefinitions() as $field_name => $definition) {
180         if (isset($entity_form[$field_name]) && $field_name != $langcode_key) {
181           $entity_form[$field_name]['#access'] = $definition->isTranslatable();
182         }
183       }
184     }
185     // Allow other modules to alter the form.
186     $this->moduleHandler->alter('inline_entity_form_entity_form', $entity_form, $form_state);
187
188     return $entity_form;
189   }
190
191   /**
192    * {@inheritdoc}
193    */
194   public function entityFormValidate(array &$entity_form, FormStateInterface $form_state) {
195     // Perform entity validation only if the inline form was submitted,
196     // skipping other requests such as file uploads.
197     $triggering_element = $form_state->getTriggeringElement();
198     if (!empty($triggering_element['#ief_submit_trigger'])) {
199       /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
200       $entity = $entity_form['#entity'];
201       $this->buildEntity($entity_form, $entity, $form_state);
202       $form_display = $this->getFormDisplay($entity, $entity_form['#form_mode']);
203       $form_display->validateFormValues($entity, $entity_form, $form_state);
204       $entity->setValidationRequired(FALSE);
205
206       foreach($form_state->getErrors() as $name => $message) {
207         // $name may be unknown in $form_state and
208         // $form_state->setErrorByName($name, $message) may suppress the error message.
209         $form_state->setError($triggering_element, $message);
210       }
211     }
212   }
213
214   /**
215    * {@inheritdoc}
216    */
217   public function entityFormSubmit(array &$entity_form, FormStateInterface $form_state) {
218     $form_state->cleanValues();
219     /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
220     $entity = $entity_form['#entity'];
221     $this->buildEntity($entity_form, $entity, $form_state);
222   }
223
224   /**
225    * {@inheritdoc}
226    */
227   public function save(EntityInterface $entity) {
228     $entity->save();
229   }
230
231   /**
232    * {@inheritdoc}
233    */
234   public function delete($ids, $context) {
235     $storage_handler = $this->entityTypeManager->getStorage($this->entityType->id());
236     $entities = $storage_handler->loadMultiple($ids);
237     $storage_handler->delete($entities);
238   }
239
240   /**
241    * Builds an updated entity object based upon the submitted form values.
242    *
243    * @param array $entity_form
244    *   The entity form.
245    * @param \Drupal\Core\Entity\ContentEntityInterface $entity
246    *   The entity.
247    * @param \Drupal\Core\Form\FormStateInterface $form_state
248    *   The current state of the form.
249    */
250   protected function buildEntity(array $entity_form, ContentEntityInterface $entity, FormStateInterface $form_state) {
251     $form_display = $this->getFormDisplay($entity, $entity_form['#form_mode']);
252     $form_display->extractFormValues($entity, $entity_form, $form_state);
253     // Invoke all specified builders for copying form values to entity fields.
254     if (isset($entity_form['#entity_builders'])) {
255       foreach ($entity_form['#entity_builders'] as $function) {
256         call_user_func_array($function, [$entity->getEntityTypeId(), $entity, &$entity_form, &$form_state]);
257       }
258     }
259   }
260
261   /**
262    * Cleans up the form state for a submitted entity form.
263    *
264    * After field_attach_submit() has run and the form has been closed, the form
265    * state still contains field data in $form_state->get('field'). Unless that
266    * data is removed, the next form with the same #parents (reopened add form,
267    * for example) will contain data (i.e. uploaded files) from the previous form.
268    *
269    * @param $entity_form
270    *   The entity form.
271    * @param $form_state
272    *   The form state of the parent form.
273    */
274   public static function submitCleanFormState(&$entity_form, FormStateInterface $form_state) {
275     /** @var \Drupal\Core\Entity\EntityInterface $entity */
276     $entity = $entity_form['#entity'];
277     $bundle = $entity->bundle();
278     /** @var \Drupal\Core\Field\FieldDefinitionInterface[] $instances */
279     $instances = \Drupal::service('entity_field.manager')->getFieldDefinitions($entity_form['#entity_type'], $bundle);
280     foreach ($instances as $instance) {
281       $field_name = $instance->getName();
282       if (!empty($entity_form[$field_name]['#parents'])) {
283         $parents = $entity_form[$field_name]['#parents'];
284         array_pop($parents);
285         if (!empty($parents)) {
286           $field_state = [];
287           WidgetBase::setWidgetState($parents, $field_name, $form_state, $field_state);
288         }
289       }
290     }
291   }
292
293   /**
294    * Gets the form display for the given entity.
295    *
296    * @param \Drupal\Core\Entity\ContentEntityInterface $entity
297    *   The entity.
298    * @param string $form_mode
299    *   The form mode.
300    *
301    * @return \Drupal\Core\Entity\Display\EntityFormDisplayInterface
302    *   The form display.
303    */
304   protected function getFormDisplay(ContentEntityInterface $entity, $form_mode) {
305     return EntityFormDisplay::collectRenderDisplay($entity, $form_mode);
306   }
307
308 }