FieldOverview.php 19.6 KB
Newer Older
1
2
3
4
<?php

/**
 * @file
5
 * Contains \Drupal\field_ui\FieldOverview.
6
7
8
9
 */

namespace Drupal\field_ui;

10
use Drupal\Core\Entity\EntityListBuilderInterface;
11
use Drupal\Core\Entity\EntityManagerInterface;
12
use Drupal\Core\Extension\ModuleHandlerInterface;
13
use Drupal\Core\Field\FieldTypePluginManagerInterface;
14
use Drupal\Core\Render\Element;
15
use Drupal\field_ui\OverviewBase;
16
use Symfony\Component\DependencyInjection\ContainerInterface;
17
use Drupal\field\Entity\FieldConfig;
18
use Drupal\field\FieldInstanceConfigInterface;
19
20
21
22
23
24

/**
 * Field UI field overview form.
 */
class FieldOverview extends OverviewBase {

25
26
27
  /**
   *  The field type manager.
   *
28
   * @var \Drupal\Core\Field\FieldTypePluginManagerInterface
29
30
31
32
33
34
   */
  protected $fieldTypeManager;

  /**
   * Constructs a new FieldOverview.
   *
35
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
36
   *   The entity manager.
37
   * @param \Drupal\Core\Field\FieldTypePluginManagerInterface $field_type_manager
38
39
   *   The field type manager
   */
40
  public function __construct(EntityManagerInterface $entity_manager, FieldTypePluginManagerInterface $field_type_manager) {
41
    parent::__construct($entity_manager);
42
43
44
45
46
47
48
49
    $this->fieldTypeManager = $field_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
50
      $container->get('entity.manager'),
51
      $container->get('plugin.manager.field.field_type')
52
53
54
    );
  }

55
56
57
  /**
   * {@inheritdoc}
   */
58
59
60
  public function getRegions() {
    return array(
      'content' => array(
61
        'title' => $this->t('Content'),
62
        'invisible' => TRUE,
63
        // @todo Bring back this message in https://drupal.org/node/1963340.
64
        //'message' => $this->t('No fields are present yet.'),
65
66
67
68
69
      ),
    );
  }

  /**
70
   * {@inheritdoc}
71
   */
72
  public function getFormId() {
73
74
    return 'field_ui_field_overview_form';
  }
75

76
  /**
77
   * {@inheritdoc}
78
   */
79
80
  public function buildForm(array $form, array &$form_state, $entity_type_id = NULL, $bundle = NULL) {
    parent::buildForm($form, $form_state, $entity_type_id, $bundle);
81

82
    // Gather bundle information.
83
84
85
    $instances = array_filter(\Drupal::entityManager()->getFieldDefinitions($this->entity_type, $this->bundle), function ($field_definition) {
      return $field_definition instanceof FieldInstanceConfigInterface;
    });
86
    $field_types = $this->fieldTypeManager->getDefinitions();
87

88
    // Field prefix.
89
    $field_prefix = \Drupal::config('field_ui.settings')->get('field_prefix');
90

91
92
93
94
95
96
97
98
99
100
    $form += array(
      '#entity_type' => $this->entity_type,
      '#bundle' => $this->bundle,
      '#fields' => array_keys($instances),
    );

    $table = array(
      '#type' => 'field_ui_table',
      '#tree' => TRUE,
      '#header' => array(
101
        $this->t('Label'),
102
103
104
105
        array(
          'data' => $this->t('Machine name'),
          'class' => array(RESPONSIVE_PRIORITY_MEDIUM),
        ),
106
107
        $this->t('Field type'),
        $this->t('Operations'),
108
109
110
111
112
113
114
115
116
117
      ),
      '#regions' => $this->getRegions(),
      '#attributes' => array(
        'class' => array('field-ui-overview'),
        'id' => 'field-overview',
      ),
    );

    // Fields.
    foreach ($instances as $name => $instance) {
118
      $field = $instance->getField();
119
120
      $route_parameters = array(
        $this->bundleEntityType => $this->bundle,
121
        'field_instance_config' => $instance->id(),
122
      );
123
      $table[$name] = array(
124
125
126
        '#attributes' => array(
          'id' => drupal_html_class($name),
        ),
127
        'label' => array(
128
          '#markup' => check_plain($instance->getLabel()),
129
130
        ),
        'field_name' => array(
131
          '#markup' => $instance->getName(),
132
133
134
        ),
        'type' => array(
          '#type' => 'link',
135
          '#title' => $field_types[$field->getType()]['label'],
136
137
          '#route_name' => 'field_ui.field_edit_' . $this->entity_type,
          '#route_parameters' => $route_parameters,
138
          '#options' => array('attributes' => array('title' => $this->t('Edit field settings.'))),
139
140
141
142
143
        ),
      );

      $table[$name]['operations']['data'] = array(
        '#type' => 'operations',
144
        '#links' => $this->entityManager->getListBuilder('field_instance_config')->getOperations($instance),
145
146
      );

147
      if (!empty($field->locked)) {
148
        $table[$name]['operations'] = array('#markup' => $this->t('Locked'));
149
150
151
152
        $table[$name]['#attributes']['class'][] = 'menu-disabled';
      }
    }

153
154
155
    // Gather valid field types.
    $field_type_options = array();
    foreach ($field_types as $name => $field_type) {
156
157
      // Skip field types which should not be added via user interface.
      if (empty($field_type['no_ui'])) {
158
159
160
161
162
        $field_type_options[$name] = $field_type['label'];
      }
    }
    asort($field_type_options);

163
164
    // Additional row: add new field.
    if ($field_type_options) {
165
166
      $name = '_add_new_field';
      $table[$name] = array(
167
        '#attributes' => array('class' => array('add-new')),
168
169
        'label' => array(
          '#type' => 'textfield',
170
          '#title' => $this->t('New field label'),
171
172
          '#title_display' => 'invisible',
          '#size' => 15,
173
174
          '#description' => $this->t('Label'),
          '#prefix' => '<div class="label-input"><div class="add-new-placeholder">' . $this->t('Add new field') .'</div>',
175
176
177
178
          '#suffix' => '</div>',
        ),
        'field_name' => array(
          '#type' => 'machine_name',
179
          '#title' => $this->t('New field name'),
180
181
          '#title_display' => 'invisible',
          // This field should stay LTR even for RTL languages.
182
          '#field_prefix' => '<span dir="ltr">' . $field_prefix,
183
184
          '#field_suffix' => '</span>&lrm;',
          '#size' => 15,
185
          '#description' => $this->t('A unique machine-readable name containing letters, numbers, and underscores.'),
186
187
          // Calculate characters depending on the length of the field prefix
          // setting. Maximum length is 32.
188
          '#maxlength' => FieldConfig::NAME_MAX_LENGTH - strlen($field_prefix),
189
190
191
          '#prefix' => '<div class="add-new-placeholder">&nbsp;</div>',
          '#machine_name' => array(
            'source' => array('fields', $name, 'label'),
192
            'exists' => array($this, 'fieldNameExists'),
193
194
195
196
197
198
199
            'standalone' => TRUE,
            'label' => '',
          ),
          '#required' => FALSE,
        ),
        'type' => array(
          '#type' => 'select',
200
          '#title' => $this->t('Type of new field'),
201
202
          '#title_display' => 'invisible',
          '#options' => $field_type_options,
203
204
          '#empty_option' => $this->t('- Select a field type -'),
          '#description' => $this->t('Type of data to store.'),
205
          '#attributes' => array('class' => array('field-type-select')),
206
          '#cell_attributes' => array('colspan' => 2),
207
208
209
210
211
212
213
214
215
216
217
218
          '#prefix' => '<div class="add-new-placeholder">&nbsp;</div>',
        ),
        // Place the 'translatable' property as an explicit value so that
        // contrib modules can form_alter() the value for newly created fields.
        'translatable' => array(
          '#type' => 'value',
          '#value' => FALSE,
        ),
      );
    }

    // Additional row: re-use existing field.
219
    $existing_fields = $this->getExistingFieldOptions();
220
    if ($existing_fields) {
221
222
223
      // Build list of options.
      $existing_field_options = array();
      foreach ($existing_fields as $field_name => $info) {
224
        $text = $this->t('@type: @field (@label)', array(
225
226
227
228
229
230
231
232
233
          '@type' => $info['type_label'],
          '@label' => $info['label'],
          '@field' => $info['field'],
        ));
        $existing_field_options[$field_name] = truncate_utf8($text, 80, FALSE, TRUE);
      }
      asort($existing_field_options);
      $name = '_add_existing_field';
      $table[$name] = array(
234
        '#attributes' => array('class' => array('add-new')),
235
        '#row_type' => 'add_new_field',
236
        '#region_callback' => array($this, 'getRowRegion'),
237
238
        'label' => array(
          '#type' => 'textfield',
239
          '#title' => $this->t('Existing field label'),
240
241
          '#title_display' => 'invisible',
          '#size' => 15,
242
          '#description' => $this->t('Label'),
243
          '#attributes' => array('class' => array('label-textfield')),
244
          '#prefix' => '<div class="label-input"><div class="add-new-placeholder">' . $this->t('Re-use existing field') .'</div>',
245
246
247
248
          '#suffix' => '</div>',
        ),
        'field_name' => array(
          '#type' => 'select',
249
          '#title' => $this->t('Existing field to share'),
250
251
          '#title_display' => 'invisible',
          '#options' => $existing_field_options,
252
253
          '#empty_option' => $this->t('- Select an existing field -'),
          '#description' => $this->t('Field to share'),
254
255
256
257
258
259
260
          '#attributes' => array('class' => array('field-select')),
          '#cell_attributes' => array('colspan' => 3),
          '#prefix' => '<div class="add-new-placeholder">&nbsp;</div>',
        ),
      );
    }

261
262
263
    // We can set the 'rows_order' element, needed by theme_field_ui_table(),
    // here instead of a #pre_render callback because this form doesn't have the
    // tabledrag behavior anymore.
264
    $table['#regions']['content']['rows_order'] = array();
265
    foreach (Element::children($table) as $name) {
266
267
      $table['#regions']['content']['rows_order'][] = $name;
    }
268

269
    $form['fields'] = $table;
270
271

    $form['actions'] = array('#type' => 'actions');
272
273
274
275
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#button_type' => 'primary',
      '#value' => $this->t('Save'));
276
277
278
279
280

    return $form;
  }

  /**
281
   * {@inheritdoc}
282
   */
283
  public function validateForm(array &$form, array &$form_state) {
284
285
286
287
288
289
290
291
292
293
294
295
    $this->validateAddNew($form, $form_state);
    $this->validateAddExisting($form, $form_state);
  }

  /**
   * Validates the 'add new field' row.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param array $form_state
   *   A reference to a keyed array containing the current state of the form.
   *
296
   * @see \Drupal\field_ui\FieldOverview::validateForm()
297
298
299
300
301
   */
  protected function validateAddNew(array $form, array &$form_state) {
    $field = $form_state['values']['fields']['_add_new_field'];

    // Validate if any information was provided in the 'add new field' row.
302
    if (array_filter(array($field['label'], $field['field_name'], $field['type']))) {
303
304
      // Missing label.
      if (!$field['label']) {
305
        $this->setFormError('fields][_add_new_field][label', $form_state, $this->t('Add new field: you need to provide a label.'));
306
307
308
309
      }

      // Missing field name.
      if (!$field['field_name']) {
310
        $this->setFormError('fields][_add_new_field][field_name', $form_state, $this->t('Add new field: you need to provide a field name.'));
311
312
313
314
315
      }
      // Field name validation.
      else {
        $field_name = $field['field_name'];

316
        // Add the field prefix.
317
        $field_name = \Drupal::config('field_ui.settings')->get('field_prefix') . $field_name;
318
319
320
321
322
        form_set_value($form['fields']['_add_new_field']['field_name'], $field_name, $form_state);
      }

      // Missing field type.
      if (!$field['type']) {
323
        $this->setFormError('fields][_add_new_field][type', $form_state, $this->t('Add new field: you need to select a field type.'));
324
325
326
327
328
329
330
331
332
333
334
335
      }
    }
  }

  /**
   * Validates the 're-use existing field' row.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param array $form_state
   *   A reference to a keyed array containing the current state of the form.
   *
336
   * @see \Drupal\field_ui\FieldOverview::validate()
337
338
339
340
341
342
343
344
345
   */
  protected function validateAddExisting(array $form, array &$form_state) {
    // The form element might be absent if no existing fields can be added to
    // this bundle.
    if (isset($form_state['values']['fields']['_add_existing_field'])) {
      $field = $form_state['values']['fields']['_add_existing_field'];

      // Validate if any information was provided in the
      // 're-use existing field' row.
346
      if (array_filter(array($field['label'], $field['field_name']))) {
347
348
        // Missing label.
        if (!$field['label']) {
349
          $this->setFormError('fields][_add_existing_field][label', $form_state, $this->t('Re-use existing field: you need to provide a label.'));
350
351
352
353
        }

        // Missing existing field name.
        if (!$field['field_name']) {
354
          $this->setFormError('fields][_add_existing_field][field_name', $form_state, $this->t('Re-use existing field: you need to select a field.'));
355
356
357
358
359
360
        }
      }
    }
  }

  /**
361
   * Overrides \Drupal\field_ui\OverviewBase::submitForm().
362
   */
363
  public function submitForm(array &$form, array &$form_state) {
364
    $error = FALSE;
365
366
367
368
369
370
371
372
    $form_values = $form_state['values']['fields'];
    $destinations = array();

    // Create new field.
    if (!empty($form_values['_add_new_field']['field_name'])) {
      $values = $form_values['_add_new_field'];

      $field = array(
373
374
        'name' => $values['field_name'],
        'entity_type' => $this->entity_type,
375
376
377
378
        'type' => $values['type'],
        'translatable' => $values['translatable'],
      );
      $instance = array(
379
        'field_name' => $values['field_name'],
380
381
382
383
384
385
386
        'entity_type' => $this->entity_type,
        'bundle' => $this->bundle,
        'label' => $values['label'],
      );

      // Create the field and instance.
      try {
387
388
        $this->entityManager->getStorage('field_config')->create($field)->save();
        $new_instance = $this->entityManager->getStorage('field_instance_config')->create($instance);
389
        $new_instance->save();
390

391
        // Make sure the field is displayed in the 'default' form mode (using
392
393
        // default widget and settings). It stays hidden for other form modes
        // until it is explicitly configured.
394
        entity_get_form_display($this->entity_type, $this->bundle, 'default')
395
          ->setComponent($values['field_name'])
396
397
          ->save();

398
399
400
401
        // Make sure the field is displayed in the 'default' view mode (using
        // default formatter and settings). It stays hidden for other view
        // modes until it is explicitly configured.
        entity_get_display($this->entity_type, $this->bundle, 'default')
402
          ->setComponent($values['field_name'])
403
404
          ->save();

405
406
        // Always show the field settings step, as the cardinality needs to be
        // configured for new fields.
407
408
        $route_parameters = array(
          $this->bundleEntityType => $this->bundle,
409
          'field_instance_config' => $new_instance->id(),
410
411
412
        );
        $destinations[] = array('route_name' => 'field_ui.field_edit_' . $this->entity_type, 'route_parameters' => $route_parameters);
        $destinations[] = array('route_name' => 'field_ui.instance_edit_' . $this->entity_type, 'route_parameters' => $route_parameters);
413
414

        // Store new field information for any additional submit handlers.
415
        $form_state['fields_added']['_add_new_field'] = $values['field_name'];
416
      }
417
      catch (\Exception $e) {
418
419
        $error = TRUE;
        drupal_set_message($this->t('There was a problem creating field %label: !message', array('%label' => $instance['label'], '!message' => $e->getMessage())), 'error');
420
421
422
423
424
425
      }
    }

    // Re-use existing field.
    if (!empty($form_values['_add_existing_field']['field_name'])) {
      $values = $form_values['_add_existing_field'];
426
427
428
      $field_name = $values['field_name'];
      $field = field_info_field($this->entity_type, $field_name);
      if (!empty($field->locked)) {
429
        drupal_set_message($this->t('The field %label cannot be added because it is locked.', array('%label' => $values['label'])), 'error');
430
431
432
      }
      else {
        $instance = array(
433
          'field_name' => $field_name,
434
435
436
437
438
439
          'entity_type' => $this->entity_type,
          'bundle' => $this->bundle,
          'label' => $values['label'],
        );

        try {
440
          $new_instance = $this->entityManager->getStorage('field_instance_config')->create($instance);
441
          $new_instance->save();
442

443
          // Make sure the field is displayed in the 'default' form mode (using
444
445
          // default widget and settings). It stays hidden for other form modes
          // until it is explicitly configured.
446
          entity_get_form_display($this->entity_type, $this->bundle, 'default')
447
            ->setComponent($field_name)
448
449
            ->save();

450
451
452
453
          // Make sure the field is displayed in the 'default' view mode (using
          // default formatter and settings). It stays hidden for other view
          // modes until it is explicitly configured.
          entity_get_display($this->entity_type, $this->bundle, 'default')
454
            ->setComponent($field_name)
455
456
            ->save();

457
458
459
460
          $destinations[] = array(
            'route_name' => 'field_ui.instance_edit_' . $this->entity_type,
            'route_parameters' => array(
              $this->bundleEntityType => $this->bundle,
461
              'field_instance_config' => $new_instance->id(),
462
463
            ),
          );
464
465
466
          // Store new field information for any additional submit handlers.
          $form_state['fields_added']['_add_existing_field'] = $instance['field_name'];
        }
467
        catch (\Exception $e) {
468
469
          $error = TRUE;
          drupal_set_message($this->t('There was a problem creating field instance %label: @message.', array('%label' => $instance['label'], '@message' => $e->getMessage())), 'error');
470
471
472
473
474
475
476
        }
      }
    }

    if ($destinations) {
      $destination = drupal_get_destination();
      $destinations[] = $destination['destination'];
477
      $form_state['redirect_route'] = FieldUI::getNextDestination($destinations, $form_state);
478
    }
479
    elseif (!$error) {
480
      drupal_set_message($this->t('Your settings have been saved.'));
481
482
    }
  }
483
484
485
486
487
488
489
490

  /**
   * Returns an array of existing fields to be added to a bundle.
   *
   * @return array
   *   An array of existing fields keyed by field name.
   */
  protected function getExistingFieldOptions() {
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
    $options = array();

    // Collect candidate field instances: all instances of fields for this
    // entity type that are not already present in the current bundle.
    $field_map = field_info_field_map();
    $instance_ids = array();
    if (!empty($field_map[$this->entity_type])) {
      foreach ($field_map[$this->entity_type] as $field_name => $data) {
        if (!in_array($this->bundle, $data['bundles'])) {
          $bundle = reset($data['bundles']);
          $instance_ids[] = $this->entity_type . '.' . $bundle . '.' . $field_name;
        }
      }
    }

    // Load the instances and build the list of options.
    if ($instance_ids) {
      $field_types = $this->fieldTypeManager->getDefinitions();
509
      $instances = $this->entityManager->getStorage('field_instance_config')->loadMultiple($instance_ids);
510
511
512
513
      foreach ($instances as $instance) {
        // Do not show:
        // - locked fields,
        // - fields that should not be added via user interface.
514
        $field_type = $instance->getType();
515
516
        $field = $instance->getField();
        if (empty($field->locked) && empty($field_types[$field_type]['no_ui'])) {
517
          $options[$instance->getName()] = array(
518
519
            'type' => $field_type,
            'type_label' => $field_types[$field_type]['label'],
520
521
            'field' => $instance->getName(),
            'label' => $instance->getLabel(),
522
          );
523
524
525
        }
      }
    }
526
527

    return $options;
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
  }

  /**
   * Checks if a field machine name is taken.
   *
   * @param string $value
   *   The machine name, not prefixed with 'field_'.
   *
   * @return bool
   *   Whether or not the field machine name is taken.
   */
  public function fieldNameExists($value) {
    // Prefix with 'field_'.
    $field_name = 'field_' . $value;

543
    return (bool) field_info_field($this->entity_type, $field_name);
544
545
  }

546
}