ConfigurableEntityReferenceItem.php 8.25 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\entity_reference\ConfigurableEntityReferenceItem.
6 7
 */

8
namespace Drupal\entity_reference;
9

10 11 12
use Drupal\Component\Utility\String;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\TypedData\AllowedValuesInterface;
13
use Drupal\Core\TypedData\DataDefinition;
14
use Drupal\Core\Field\FieldDefinitionInterface;
15 16
use Drupal\Core\Field\ConfigEntityReferenceItemBase;
use Drupal\Core\Field\ConfigFieldItemInterface;
17
use Drupal\Core\Validation\Plugin\Validation\Constraint\AllowedValuesConstraint;
18 19

/**
20
 * Alternative plugin implementation of the 'entity_reference' field type.
21
 *
22 23
 * Replaces the Core 'entity_reference' entity field type implementation, this
 * supports configurable fields, auto-creation of referenced entities and more.
24
 *
25 26 27
 * Required settings (below the definition's 'settings' key) are:
 *  - target_type: The entity type to reference.
 *
28
 * @see entity_reference_field_info_alter().
29 30
 *
 */
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
class ConfigurableEntityReferenceItem extends ConfigEntityReferenceItemBase implements ConfigFieldItemInterface, AllowedValuesInterface {

  /**
   * {@inheritdoc}
   */
  public function getPossibleValues(AccountInterface $account = NULL) {
    return $this->getSettableValues($account);
  }

  /**
   * {@inheritdoc}
   */
  public function getPossibleOptions(AccountInterface $account = NULL) {
    return $this->getSettableOptions($account);
  }

  /**
   * {@inheritdoc}
   */
  public function getSettableValues(AccountInterface $account = NULL) {
    // Flatten options firstly, because Settable Options may contain group
    // arrays.
    $flatten_options = \Drupal::formBuilder()->flattenOptions($this->getSettableOptions($account));
    return array_keys($flatten_options);
  }

  /**
   * {@inheritdoc}
   */
  public function getSettableOptions(AccountInterface $account = NULL) {
    $field_definition = $this->getFieldDefinition();
    if (!$options = \Drupal::service('plugin.manager.entity_reference.selection')->getSelectionHandler($field_definition, $this->getEntity())->getReferenceableEntities()) {
      return array();
    }

    // Rebuild the array by changing the bundle key into the bundle label.
    $target_type = $field_definition->getSetting('target_type');
    $bundles = \Drupal::entityManager()->getBundleInfo($target_type);

    $return = array();
    foreach ($options as $bundle => $entity_ids) {
      $bundle_label = String::checkPlain($bundles[$bundle]['label']);
      $return[$bundle_label] = $entity_ids;
    }

    return count($return) == 1 ? reset($return) : $return;
  }
78

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
  /**
   * Definitions of the contained properties.
   *
   * @see ConfigurableEntityReferenceItem::getPropertyDefinitions()
   *
   * @var array
   */
  static $propertyDefinitions;

  /**
   * {@inheritdoc}
   */
  public function getPropertyDefinitions() {
    $settings = $this->definition->getSettings();
    $target_type = $settings['target_type'];

    // Definitions vary by entity type and bundle, so key them accordingly.
    $key = $target_type . ':';
    $key .= isset($settings['target_bundle']) ? $settings['target_bundle'] : '';

    if (!isset(static::$propertyDefinitions[$key])) {
      // Call the parent to define the target_id and entity properties.
      parent::getPropertyDefinitions();

      // Only add the revision ID property if the target entity type supports
      // revisions.
      $target_type_info = \Drupal::entityManager()->getDefinition($target_type);
106
      if ($target_type_info->hasKey('revision') && $target_type_info->getRevisionTable()) {
107 108 109 110 111 112 113 114 115
        static::$propertyDefinitions[$key]['revision_id'] = DataDefinition::create('integer')
          ->setLabel(t('Revision ID'))
          ->setConstraints(array('Range' => array('min' => 0)));
      }
    }

    return static::$propertyDefinitions[$key];
  }

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
    $constraints = parent::getConstraints();

    // Remove the 'AllowedValuesConstraint' validation constraint because entity
    // reference fields already use the 'ValidReference' constraint.
    foreach ($constraints as $key => $constraint) {
      if ($constraint instanceof AllowedValuesConstraint) {
        unset($constraints[$key]);
      }
    }

    return $constraints;
  }

133 134 135
  /**
   * {@inheritdoc}
   */
136 137 138 139
  public static function schema(FieldDefinitionInterface $field_definition) {
    $schema = parent::schema($field_definition);

    $target_type = $field_definition->getSetting('target_type');
140 141
    $target_type_info = \Drupal::entityManager()->getDefinition($target_type);

142
    if ($target_type_info->isSubclassOf('\Drupal\Core\Entity\ContentEntityInterface')) {
143 144 145 146 147
      $schema['columns']['revision_id'] = array(
        'description' => 'The revision ID of the target entity.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => FALSE,
148 149 150
      );
    }

151 152 153 154 155 156 157 158 159 160
    return $schema;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, array &$form_state, $has_data) {
    $element['target_type'] = array(
      '#type' => 'select',
      '#title' => t('Type of item to reference'),
161
      '#options' => \Drupal::entityManager()->getEntityTypeLabels(),
162 163 164 165 166 167 168 169 170 171 172 173 174
      '#default_value' => $this->getFieldSetting('target_type'),
      '#required' => TRUE,
      '#disabled' => $has_data,
      '#size' => 1,
    );

    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function instanceSettingsForm(array $form, array &$form_state) {
175
    $instance = $form_state['instance'];
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212

    // Get all selection plugins for this entity type.
    $selection_plugins = \Drupal::service('plugin.manager.entity_reference.selection')->getSelectionGroups($this->getFieldSetting('target_type'));
    $handler_groups = array_keys($selection_plugins);

    $handlers = \Drupal::service('plugin.manager.entity_reference.selection')->getDefinitions();
    $handlers_options = array();
    foreach ($handlers as $plugin_id => $plugin) {
      // We only display base plugins (e.g. 'default', 'views', ...) and not
      // entity type specific plugins (e.g. 'default_node', 'default_user',
      // ...).
      if (in_array($plugin_id, $handler_groups)) {
        $handlers_options[$plugin_id] = check_plain($plugin['label']);
      }
    }

    $form = array(
      '#type' => 'container',
      '#attached' => array(
        'css' => array(drupal_get_path('module', 'entity_reference') . '/css/entity_reference.admin.css'),
      ),
      '#process' => array(
        '_entity_reference_field_instance_settings_ajax_process',
      ),
      '#element_validate' => array(array(get_class($this), 'instanceSettingsFormValidate')),
    );
    $form['handler'] = array(
      '#type' => 'details',
      '#title' => t('Reference type'),
      '#tree' => TRUE,
      '#process' => array('_entity_reference_form_process_merge_parent'),
    );

    $form['handler']['handler'] = array(
      '#type' => 'select',
      '#title' => t('Reference method'),
      '#options' => $handlers_options,
213
      '#default_value' => $instance->getSetting('handler'),
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
      '#required' => TRUE,
      '#ajax' => TRUE,
      '#limit_validation_errors' => array(),
    );
    $form['handler']['handler_submit'] = array(
      '#type' => 'submit',
      '#value' => t('Change handler'),
      '#limit_validation_errors' => array(),
      '#attributes' => array(
        'class' => array('js-hide'),
      ),
      '#submit' => array('entity_reference_settings_ajax_submit'),
    );

    $form['handler']['handler_settings'] = array(
      '#type' => 'container',
      '#attributes' => array('class' => array('entity_reference-settings')),
    );

233 234
    $handler = \Drupal::service('plugin.manager.entity_reference.selection')->getSelectionHandler($instance);
    $form['handler']['handler_settings'] += $handler->settingsForm($instance);
235 236 237 238 239 240 241 242 243 244 245 246

    return $form;
  }

  /**
   * Form element validation handler; Stores the new values in the form state.
   *
   * @param array $form
   *   The form where the settings form is being included in.
   * @param array $form_state
   *   The form state of the (entire) configuration form.
   */
alexpott's avatar
alexpott committed
247
  public static function instanceSettingsFormValidate(array $form, array &$form_state) {
248 249
    if (isset($form_state['values']['instance'])) {
      unset($form_state['values']['instance']['settings']['handler_submit']);
250
      $form_state['instance']->settings = $form_state['values']['instance']['settings'];
251 252 253 254
    }
  }

}