Beispiel #1
0
 /**
  * Overrides \Drupal\views\Plugin\views\filter\InOperator::init().
  */
 public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL)
 {
     parent::init($view, $display, $options);
     $this->entityTypeId = $this->getEntityType();
     $this->entityType = \Drupal::entityManager()->getDefinition($this->entityTypeId);
     $this->real_field = $this->entityType->getKey('bundle');
 }
Beispiel #2
0
 /**
  * {@inheritdoc}
  */
 public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL)
 {
     parent::init($view, $display, $options);
     $this->entityTypeId = $this->definition['entity_type'];
     $this->entityType = $this->entityManager->getDefinition($this->entityTypeId);
     $this->base_table = $this->entityType->getDataTable() ?: $this->entityType->getBaseTable();
     $this->base_field = $this->entityType->getKey('id');
 }
 /**
  * Constructs an EntityStorageBase instance.
  *
  * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
  *   The entity type definition.
  */
 public function __construct(EntityTypeInterface $entity_type)
 {
     $this->entityTypeId = $entity_type->id();
     $this->entityType = $entity_type;
     $this->idKey = $this->entityType->getKey('id');
     $this->uuidKey = $this->entityType->getKey('uuid');
     $this->entityClass = $this->entityType->getClass();
 }
Beispiel #4
0
 /**
  * Loads entity IDs using a pager sorted by the entity id.
  *
  * @return array
  *   An array of entity IDs.
  */
 protected function getEntityIds()
 {
     $query = $this->getStorage()->getQuery()->sort($this->entityType->getKey('id'));
     // Only add the pager if a limit is specified.
     if ($this->limit) {
         $query->pager($this->limit);
     }
     return $query->execute();
 }
Beispiel #5
0
 /**
  * Processes the views data for an entity reference field.
  *
  * @param string $table
  *   The table the language field is added to.
  * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
  *   The field definition.
  * @param array $views_field
  *   The views field data.
  * @param string $field_column_name
  *   The field column being processed.
  */
 protected function processViewsDataForEntityReference($table, FieldDefinitionInterface $field_definition, array &$views_field, $field_column_name)
 {
     // @todo Should the actual field handler respect that this just renders a
     //   number?
     // @todo Create an optional entity field handler, that can render the
     //   entity.
     // @see https://www.drupal.org/node/2322949
     if ($entity_type_id = $field_definition->getItemDefinition()->getSetting('target_type')) {
         $entity_type = $this->entityManager->getDefinition($entity_type_id);
         if ($entity_type instanceof ContentEntityType) {
             $views_field['relationship'] = ['base' => $this->getViewsTableForEntityType($entity_type), 'base field' => $entity_type->getKey('id'), 'label' => $entity_type->getLabel(), 'title' => $entity_type->getLabel(), 'id' => 'standard'];
             $views_field['field']['id'] = 'field';
             $views_field['argument']['id'] = 'numeric';
             $views_field['filter']['id'] = 'numeric';
             $views_field['sort']['id'] = 'standard';
         } else {
             $views_field['field']['id'] = 'field';
             $views_field['argument']['id'] = 'string';
             $views_field['filter']['id'] = 'string';
             $views_field['sort']['id'] = 'standard';
         }
     }
     if ($field_definition->getName() == $this->entityType->getKey('bundle')) {
         $views_field['filter']['id'] = 'bundle';
     }
 }
 /**
  * Retrieves filter information based on user input for the default display.
  *
  * @param array $form
  *   The full wizard form array.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the wizard form.
  *
  * @return array
  *   An array of filter arrays keyed by ID. A sort array contains the options
  *   accepted by a filter handler.
  */
 protected function defaultDisplayFiltersUser(array $form, FormStateInterface $form_state)
 {
     $filters = array();
     if (($type = $form_state->getValue(array('show', 'type'))) && $type != 'all') {
         $bundle_key = $this->entityType->getKey('bundle');
         // Figure out the table where $bundle_key lives. It may not be the same as
         // the base table for the view; the taxonomy vocabulary machine_name, for
         // example, is stored in taxonomy_vocabulary, not taxonomy_term_data.
         module_load_include('inc', 'views_ui', 'admin');
         $fields = Views::viewsDataHelper()->fetchFields($this->base_table, 'filter');
         if (isset($fields[$this->base_table . '.' . $bundle_key])) {
             $table = $this->base_table;
         } else {
             foreach ($fields as $field_name => $value) {
                 if ($pos = strpos($field_name, '.' . $bundle_key)) {
                     $table = substr($field_name, 0, $pos);
                     break;
                 }
             }
         }
         $table_data = Views::viewsData()->get($table);
         // If the 'in' operator is being used, map the values to an array.
         $handler = $table_data[$bundle_key]['filter']['id'];
         $handler_definition = Views::pluginManager('filter')->getDefinition($handler);
         if ($handler == 'in_operator' || is_subclass_of($handler_definition['class'], 'Drupal\\views\\Plugin\\views\\filter\\InOperator')) {
             $value = array($type => $type);
         } else {
             $value = $type;
         }
         $filters[$bundle_key] = array('id' => $bundle_key, 'table' => $table, 'field' => $bundle_key, 'value' => $value);
     }
     return $filters;
 }
Beispiel #7
0
 /**
  * {@inheritdoc}
  */
 public function buildAdvancedForm(array $form, FormStateInterface $form_state)
 {
     if ($bundle_key = $this->entityType->getKey('bundle')) {
         $form['values'][$bundle_key] = ['#type' => 'select', '#options' => $this->bundleOptions(), '#title' => $this->bundleLabel(), '#required' => TRUE, '#default_value' => $this->bundle() ?: key($this->bundleOptions()), '#disabled' => $this->isLocked()];
     }
     return $form;
 }
 /**
  * Returns the add page route.
  *
  * Built only for entity types that have bundles.
  *
  * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
  *   The entity type.
  *
  * @return \Symfony\Component\Routing\Route|null
  *   The generated route, if available.
  */
 protected function addPageRoute(EntityTypeInterface $entity_type)
 {
     if ($entity_type->hasLinkTemplate('add-page') && $entity_type->getKey('bundle')) {
         $route = new Route($entity_type->getLinkTemplate('add-page'));
         $route->setDefault('_controller', '\\Drupal\\entity\\Controller\\EntityCreateController::addPage');
         $route->setDefault('_title_callback', '\\Drupal\\entity\\Controller\\EntityCreateController::addPageTitle');
         $route->setDefault('entity_type_id', $entity_type->id());
         $route->setRequirement('_entity_create_access', $entity_type->id());
         return $route;
     }
 }
 /**
  * Returns a mock entity for testing.
  *
  * @param string $class
  *   The class name to mock. Should be \Drupal\Core\Entity\Entity or a
  *   subclass.
  * @param array $values
  *   An array of entity values to construct the mock entity with.
  * @param array $methods
  *   (optional) An array of additional methods to mock on the entity object.
  *   The getEntityType() and entityManager() methods are always mocked.
  *
  * @return \Drupal\Core\Entity\Entity|\PHPUnit_Framework_MockObject_MockObject
  */
 protected function getEntity($class, array $values, array $methods = [])
 {
     $methods = array_merge($methods, ['getEntityType', 'entityManager']);
     // Prophecy does not allow prophesizing abstract classes while actually
     // calling their code. We use Prophecy below because that allows us to
     // add method prophecies later while still revealing the prophecy now.
     $entity = $this->getMockBuilder($class)->setConstructorArgs([$values, $this->entityTypeId])->setMethods($methods)->getMockForAbstractClass();
     $this->entityType = $this->prophesize(EntityTypeInterface::class);
     $this->entityType->getLinkTemplates()->willReturn([]);
     $this->entityType->getKey('langcode')->willReturn(FALSE);
     $entity->method('getEntityType')->willReturn($this->entityType->reveal());
     $this->entityManager = $this->prophesize(EntityManagerInterface::class);
     $entity->method('entityManager')->willReturn($this->entityManager->reveal());
     return $entity;
 }
Beispiel #10
0
  /**
   * Gets the entities that can be filtered by.
   *
   * @return \Drupal\Core\Entity\EntityInterface[]
   */
  protected function getReferenceableEntities() {
    if ($this->referenceableEntities !== NULL) {
      return $this->referenceableEntities;
    }
    $target_ids = NULL;

    // Filter by bundle if if the plugin was configured to do so.
    $target_bundles = array_filter($this->options['verf_target_bundles']);
    if ($this->targetEntityType->hasKey('bundle') && $target_bundles) {
      $query = $this->targetEntityStorage->getQuery();
      $query->condition($this->targetEntityType->getKey('bundle'), $target_bundles, 'IN');
      $target_ids = $query->execute();
    }

    $this->referenceableEntities = $this->targetEntityStorage->loadMultiple($target_ids);
    return $this->referenceableEntities;
  }
 /**
  * {@inheritdoc}
  */
 public function getTableFields($bundles)
 {
     $definitions = $this->entityFieldManager->getBaseFieldDefinitions($this->entityType->id());
     $label_key = $this->entityType->getKey('label');
     $label_field_label = t('Label');
     if ($label_key && isset($definitions[$label_key])) {
         $label_field_label = $definitions[$label_key]->getLabel();
     }
     $bundle_key = $this->entityType->getKey('bundle');
     $bundle_field_label = t('Type');
     if ($bundle_key && isset($definitions[$bundle_key])) {
         $bundle_field_label = $definitions[$bundle_key]->getLabel();
     }
     $fields = [];
     $fields['label'] = ['type' => 'label', 'label' => $label_field_label, 'weight' => 1];
     if (count($bundles) > 1) {
         $fields[$bundle_key] = ['type' => 'field', 'label' => $bundle_field_label, 'weight' => 2, 'display_options' => ['type' => 'entity_reference_label', 'settings' => ['link' => FALSE]]];
     }
     return $fields;
 }
 /**
  * Gets the type of the ID key for a given entity type.
  *
  * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
  *   An entity type.
  *
  * @return string|null
  *   The type of the ID key for a given entity type, or NULL if the entity
  *   type does not support fields.
  */
 protected function getEntityTypeIdKeyType(EntityTypeInterface $entity_type)
 {
     if (!$entity_type->isSubclassOf(FieldableEntityInterface::class)) {
         return NULL;
     }
     $field_storage_definitions = $this->entityFieldManager->getFieldStorageDefinitions($entity_type->id());
     return $field_storage_definitions[$entity_type->getKey('id')]->getType();
 }
 /**
  * {@inheritdoc}
  */
 public function entityFormAlter(array &$form, FormStateInterface $form_state, EntityInterface $entity)
 {
     $form_object = $form_state->getFormObject();
     $form_langcode = $form_object->getFormLangcode($form_state);
     $entity_langcode = $entity->getUntranslated()->language()->getId();
     $source_langcode = $this->getSourceLangcode($form_state);
     $new_translation = !empty($source_langcode);
     $translations = $entity->getTranslationLanguages();
     if ($new_translation) {
         // Make sure a new translation does not appear as existing yet.
         unset($translations[$form_langcode]);
     }
     $is_translation = !$form_object->isDefaultFormLangcode($form_state);
     $has_translations = count($translations) > 1;
     // Adjust page title to specify the current language being edited, if we
     // have at least one translation.
     $languages = $this->languageManager->getLanguages();
     if (isset($languages[$form_langcode]) && ($has_translations || $new_translation)) {
         $title = $this->entityFormTitle($entity);
         // When editing the original values display just the entity label.
         if ($form_langcode != $entity_langcode) {
             $t_args = array('%language' => $languages[$form_langcode]->getName(), '%title' => $entity->label(), '!title' => $title);
             $title = empty($source_langcode) ? t('!title [%language translation]', $t_args) : t('Create %language translation of %title', $t_args);
         }
         $form['#title'] = $title;
     }
     // Display source language selector only if we are creating a new
     // translation and there are at least two translations available.
     if ($has_translations && $new_translation) {
         $form['source_langcode'] = array('#type' => 'details', '#title' => t('Source language: @language', array('@language' => $languages[$source_langcode]->getName())), '#tree' => TRUE, '#weight' => -100, '#multilingual' => TRUE, 'source' => array('#title' => t('Select source language'), '#title_display' => 'invisible', '#type' => 'select', '#default_value' => $source_langcode, '#options' => array()), 'submit' => array('#type' => 'submit', '#value' => t('Change'), '#submit' => array(array($this, 'entityFormSourceChange'))));
         foreach ($this->languageManager->getLanguages() as $language) {
             if (isset($translations[$language->getId()])) {
                 $form['source_langcode']['source']['#options'][$language->getId()] = $language->getName();
             }
         }
     }
     // Locate the language widget.
     $langcode_key = $this->entityType->getKey('langcode');
     if (isset($form[$langcode_key])) {
         $language_widget =& $form[$langcode_key];
     }
     // If we are editing the source entity, limit the list of languages so that
     // it is not possible to switch to a language for which a translation
     // already exists. Note that this will only work if the widget is structured
     // like \Drupal\Core\Field\Plugin\Field\FieldWidget\LanguageSelectWidget.
     if (isset($language_widget['widget'][0]['value']) && !$is_translation && $has_translations) {
         $language_select =& $language_widget['widget'][0]['value'];
         if ($language_select['#type'] == 'language_select') {
             $options = array();
             foreach ($this->languageManager->getLanguages() as $language) {
                 // Show the current language, and the languages for which no
                 // translation already exists.
                 if (empty($translations[$language->getId()]) || $language->getId() == $entity_langcode) {
                     $options[$language->getId()] = $language->getName();
                 }
             }
             $language_select['#options'] = $options;
         }
     }
     if ($is_translation) {
         if (isset($language_widget)) {
             $language_widget['widget']['#access'] = FALSE;
         }
         // Replace the delete button with the delete translation one.
         if (!$new_translation) {
             $weight = 100;
             foreach (array('delete', 'submit') as $key) {
                 if (isset($form['actions'][$key]['weight'])) {
                     $weight = $form['actions'][$key]['weight'];
                     break;
                 }
             }
             $access = $this->getTranslationAccess($entity, 'delete')->isAllowed() || $entity->access('delete') && $this->entityType->hasLinkTemplate('delete-form');
             $form['actions']['delete_translation'] = array('#type' => 'submit', '#value' => t('Delete translation'), '#weight' => $weight, '#submit' => array(array($this, 'entityFormDeleteTranslation')), '#access' => $access);
         }
         // Always remove the delete button on translation forms.
         unset($form['actions']['delete']);
     }
     // We need to display the translation tab only when there is at least one
     // translation available or a new one is about to be created.
     if ($new_translation || $has_translations) {
         $form['content_translation'] = array('#type' => 'details', '#title' => t('Translation'), '#tree' => TRUE, '#weight' => 10, '#access' => $this->getTranslationAccess($entity, $source_langcode ? 'create' : 'update')->isAllowed(), '#multilingual' => TRUE);
         // A new translation is enabled by default.
         $metadata = $this->manager->getTranslationMetadata($entity);
         $status = $new_translation || $metadata->isPublished();
         // If there is only one published translation we cannot unpublish it,
         // since there would be nothing left to display.
         $enabled = TRUE;
         if ($status) {
             $published = 0;
             foreach ($entity->getTranslationLanguages() as $langcode => $language) {
                 $published += $this->manager->getTranslationMetadata($entity->getTranslation($langcode))->isPublished();
             }
             $enabled = $published > 1;
         }
         $description = $enabled ? t('An unpublished translation will not be visible without translation permissions.') : t('Only this translation is published. You must publish at least one more translation to unpublish this one.');
         $form['content_translation']['status'] = array('#type' => 'checkbox', '#title' => t('This translation is published'), '#default_value' => $status, '#description' => $description, '#disabled' => !$enabled);
         $translate = !$new_translation && $metadata->isOutdated();
         if (!$translate) {
             $form['content_translation']['retranslate'] = array('#type' => 'checkbox', '#title' => t('Flag other translations as outdated'), '#default_value' => FALSE, '#description' => t('If you made a significant change, which means the other translations should be updated, you can flag all translations of this content as outdated. This will not change any other property of them, like whether they are published or not.'));
         } else {
             $form['content_translation']['outdated'] = array('#type' => 'checkbox', '#title' => t('This translation needs to be updated'), '#default_value' => $translate, '#description' => t('When this option is checked, this translation needs to be updated. Uncheck when the translation is up to date again.'));
             $form['content_translation']['#open'] = TRUE;
         }
         // Default to the anonymous user.
         $uid = 0;
         if ($new_translation) {
             $uid = $this->currentUser->id();
         } elseif (($account = $metadata->getAuthor()) && $account->id()) {
             $uid = $account->id();
         }
         $form['content_translation']['uid'] = array('#type' => 'entity_autocomplete', '#title' => t('Authored by'), '#target_type' => 'user', '#default_value' => User::load($uid), '#validate_reference' => FALSE, '#maxlength' => 60, '#description' => t('Leave blank for %anonymous.', array('%anonymous' => \Drupal::config('user.settings')->get('anonymous'))));
         $date = $new_translation ? REQUEST_TIME : $metadata->getCreatedTime();
         $form['content_translation']['created'] = array('#type' => 'textfield', '#title' => t('Authored on'), '#maxlength' => 25, '#description' => t('Format: %time. The date format is YYYY-MM-DD and %timezone is the time zone offset from UTC. Leave blank to use the time of form submission.', array('%time' => format_date(REQUEST_TIME, 'custom', 'Y-m-d H:i:s O'), '%timezone' => format_date(REQUEST_TIME, 'custom', 'O'))), '#default_value' => $new_translation || !$date ? '' : format_date($date, 'custom', 'Y-m-d H:i:s O'));
         if (isset($language_widget)) {
             $language_widget['#multilingual'] = TRUE;
         }
         $form['#process'][] = array($this, 'entityFormSharedElements');
     }
     // Process the submitted values before they are stored.
     $form['#entity_builders'][] = array($this, 'entityFormEntityBuild');
     // Handle entity validation.
     $form['#validate'][] = array($this, 'entityFormValidate');
     // Handle entity deletion.
     if (isset($form['actions']['delete'])) {
         $form['actions']['delete']['#submit'][] = array($this, 'entityFormDelete');
     }
 }
 /**
  * Gets the bundles for the current entity field.
  *
  * If the view has a non-exposed bundle filter, the bundles are taken from
  * there. Otherwise, the field's bundles are used.
  *
  * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
  *   The current entity type.
  * @param string $field_name
  *   The current field name.
  *
  * @return string[]
  *   The bundles.
  */
 protected function getBundles(EntityTypeInterface $entity_type, $field_name)
 {
     $bundles = [];
     $bundle_key = $entity_type->getKey('bundle');
     if ($bundle_key && isset($this->view->filter[$bundle_key])) {
         $filter = $this->view->filter[$bundle_key];
         if (!$filter->isExposed() && !empty($filter->value)) {
             // 'all' is added by Views and isn't a bundle.
             $bundles = array_diff($filter->value, ['all']);
         }
     }
     // Fallback to the list of bundles the field is attached to.
     if (empty($bundles)) {
         $map = $this->entityFieldManager->getFieldMap();
         $bundles = $map[$entity_type->id()][$field_name]['bundles'];
     }
     return $bundles;
 }
 /**
  * @covers ::getCanonicalRoute
  * @dataProvider providerTestGetCanonicalRoute
  */
 public function testGetCanonicalRoute(Route $expected = NULL, EntityTypeInterface $entity_type, FieldStorageDefinitionInterface $field_storage_definition = NULL)
 {
     if ($field_storage_definition) {
         $this->entityFieldManager->getFieldStorageDefinitions($entity_type->id())->willReturn([$entity_type->getKey('id') => $field_storage_definition]);
     }
     $route = $this->routeProvider->getCanonicalRoute($entity_type);
     $this->assertEquals($expected, $route);
 }
Beispiel #16
0
 /**
  * {@inheritdoc}
  *
  * Define the field properties here.
  *
  * Field name, type and size determine the table structure.
  *
  * In addition, we can define how the field and its content can be manipulated
  * in the GUI. The behaviour of the widgets used can be determined here.
  */
 public static function baseFieldDefinitions(EntityTypeInterface $entity_type)
 {
     // Standard field, used as unique if primary index.
     $fields['id'] = BaseFieldDefinition::create('uri')->setLabel(t('ID'));
     $fields['rid'] = BaseFieldDefinition::create('entity_reference')->setLabel(t('Rdf Type'))->setDescription(t('The Rdf type of this entity.'))->setSetting('target_type', 'rdf_type');
     $fields['label'] = BaseFieldDefinition::create('string')->setLabel(t('Title'))->setRequired(TRUE)->setTranslatable(TRUE)->setRevisionable(TRUE)->setSetting('max_length', 255)->setDisplayOptions('view', array('label' => 'hidden', 'type' => 'string', 'weight' => -5))->setDisplayOptions('form', array('type' => 'string_textfield', 'weight' => -5))->setDisplayConfigurable('form', TRUE)->setDisplayConfigurable('view', TRUE);
     // The UUID field is provided just to allow core or modules to retrieve RDF
     // entities by UUID. In fact UUID is computed with the same value as ID.
     $fields[$entity_type->getKey('uuid')] = BaseFieldDefinition::create('string')->setLabel(new TranslatableMarkup('UUID'))->setRevisionable(FALSE)->setReadOnly(TRUE)->setComputed(TRUE)->setCustomStorage(TRUE);
     return $fields;
 }
Beispiel #17
0
 /**
  * {@inheritdoc}
  */
 public static function baseFieldDefinitions(EntityTypeInterface $entity_type)
 {
     $fields = [];
     if ($entity_type->hasKey('id')) {
         $fields[$entity_type->getKey('id')] = BaseFieldDefinition::create('integer')->setLabel(new TranslatableMarkup('ID'))->setReadOnly(TRUE)->setSetting('unsigned', TRUE);
     }
     if ($entity_type->hasKey('uuid')) {
         $fields[$entity_type->getKey('uuid')] = BaseFieldDefinition::create('uuid')->setLabel(new TranslatableMarkup('UUID'))->setReadOnly(TRUE);
     }
     if ($entity_type->hasKey('revision')) {
         $fields[$entity_type->getKey('revision')] = BaseFieldDefinition::create('integer')->setLabel(new TranslatableMarkup('Revision ID'))->setReadOnly(TRUE)->setSetting('unsigned', TRUE);
     }
     if ($entity_type->hasKey('langcode')) {
         $fields[$entity_type->getKey('langcode')] = BaseFieldDefinition::create('language')->setLabel(new TranslatableMarkup('Language'))->setDisplayOptions('view', ['type' => 'hidden'])->setDisplayOptions('form', ['type' => 'language_select', 'weight' => 2]);
         if ($entity_type->isRevisionable()) {
             $fields[$entity_type->getKey('langcode')]->setRevisionable(TRUE);
         }
         if ($entity_type->isTranslatable()) {
             $fields[$entity_type->getKey('langcode')]->setTranslatable(TRUE);
         }
     }
     if ($entity_type->hasKey('bundle')) {
         if ($bundle_entity_type_id = $entity_type->getBundleEntityType()) {
             $fields[$entity_type->getKey('bundle')] = BaseFieldDefinition::create('entity_reference')->setLabel($entity_type->getBundleLabel())->setSetting('target_type', $bundle_entity_type_id)->setRequired(TRUE)->setReadOnly(TRUE);
         } else {
             $fields[$entity_type->getKey('bundle')] = BaseFieldDefinition::create('string')->setLabel($entity_type->getBundleLabel())->setRequired(TRUE)->setReadOnly(TRUE);
         }
     }
     return $fields;
 }