/** * Checks access to the translation overview for the entity and bundle. * * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * The parametrized route. * @param \Drupal\Core\Session\AccountInterface $account * The currently logged in account. * @param string $entity_type_id * The entity type ID. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */ public function access(RouteMatchInterface $route_match, AccountInterface $account, $entity_type_id) { /* @var \Drupal\Core\Entity\ContentEntityInterface $entity */ $entity = $route_match->getParameter($entity_type_id); if ($entity && $entity->isTranslatable()) { // Get entity base info. $bundle = $entity->bundle(); // Get entity access callback. $definition = $this->entityManager->getDefinition($entity_type_id); $translation = $definition->get('translation'); $access_callback = $translation['content_translation']['access_callback']; $access = call_user_func($access_callback, $entity); if ($access->isAllowed()) { return $access; } // Check "translate any entity" permission. if ($account->hasPermission('translate any entity')) { return AccessResult::allowed()->cachePerPermissions()->inheritCacheability($access); } // Check per entity permission. $permission = "translate {$entity_type_id}"; if ($definition->getPermissionGranularity() == 'bundle') { $permission = "translate {$bundle} {$entity_type_id}"; } return AccessResult::allowedIfHasPermission($account, $permission)->inheritCacheability($access); } // No opinion. return AccessResult::neutral(); }
/** * {@inheritdoc} */ public function setEnabled($entity_type_id, $bundle, $value) { $config = $this->loadContentLanguageSettings($entity_type_id, $bundle); $config->setThirdPartySetting('content_translation', 'enabled', $value)->save(); $entity_type = $this->entityManager->getDefinition($entity_type_id); $this->updatesManager->updateDefinitions(array($entity_type_id => $entity_type)); }
/** * Validates and upcasts request attributes. * * @todo Remove once https://drupal.org/node/1837388 is fixed. */ protected function validateAndUpcastRequestAttributes(Request $request) { // Load the entity. if (!is_object($entity = $request->attributes->get('entity'))) { $entity_id = $entity; $entity_type = $request->attributes->get('entity_type'); if (!$entity_type || !$this->entityManager->getDefinition($entity_type)) { return FALSE; } $entity = $this->entityManager->getStorage($entity_type)->load($entity_id); if (!$entity) { return FALSE; } $request->attributes->set('entity', $entity); } // Validate the field name and language. $field_name = $request->attributes->get('field_name'); if (!$field_name || !$entity->hasField($field_name)) { return FALSE; } $langcode = $request->attributes->get('langcode'); if (!$langcode || !$entity->hasTranslation($langcode)) { return FALSE; } return TRUE; }
/** * {@inheritdoc} */ public function setMapperDefinition($mapper_definition) { $this->baseEntityType = $mapper_definition['base_entity_type']; $this->baseEntityInfo = $this->entityManager->getDefinition($this->baseEntityType); $this->baseEntityBundles = $this->entityManager->getBundleInfo($this->baseEntityType); return $this; }
/** * {@inheritdoc} */ public function form(array $form, FormStateInterface $form_state) { $form = parent::form($form, $form_state); $comment_type = $this->entity; $form['label'] = array('#type' => 'textfield', '#title' => t('Label'), '#maxlength' => 255, '#default_value' => $comment_type->label(), '#required' => TRUE); $form['id'] = array('#type' => 'machine_name', '#default_value' => $comment_type->id(), '#machine_name' => array('exists' => '\\Drupal\\comment\\Entity\\CommentType::load'), '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH, '#disabled' => !$comment_type->isNew()); $form['description'] = array('#type' => 'textarea', '#default_value' => $comment_type->getDescription(), '#description' => t('Describe this comment type. The text will be displayed on the <em>Comment types</em> administration overview page.'), '#title' => t('Description')); if ($comment_type->isNew()) { $options = array(); foreach ($this->entityManager->getDefinitions() as $entity_type) { // Only expose entities that have field UI enabled, only those can // get comment fields added in the UI. if ($entity_type->get('field_ui_base_route')) { $options[$entity_type->id()] = $entity_type->getLabel(); } } $form['target_entity_type_id'] = array('#type' => 'select', '#default_value' => $comment_type->getTargetEntityTypeId(), '#title' => t('Target entity type'), '#options' => $options, '#description' => t('The target entity type can not be changed after the comment type has been created.')); } else { $form['target_entity_type_id_display'] = array('#type' => 'item', '#markup' => $this->entityManager->getDefinition($comment_type->getTargetEntityTypeId())->getLabel(), '#title' => t('Target entity type')); } if ($this->moduleHandler->moduleExists('content_translation')) { $form['language'] = array('#type' => 'details', '#title' => t('Language settings'), '#group' => 'additional_settings'); $language_configuration = ContentLanguageSettings::loadByEntityTypeBundle('comment', $comment_type->id()); $form['language']['language_configuration'] = array('#type' => 'language_configuration', '#entity_information' => array('entity_type' => 'comment', 'bundle' => $comment_type->id()), '#default_value' => $language_configuration); $form['#submit'][] = 'language_configuration_element_submit'; } $form['actions'] = array('#type' => 'actions'); $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Save')); return $form; }
/** * {@inheritdoc} */ public function getDerivativeDefinitions($base_plugin_definition) { $this->derivatives = []; /** @var \Drupal\rng\Entity\EventType[] $event_types */ foreach ($this->eventManager->getEventTypes() as $entity_type => $event_types) { $cache_tags = $this->entityManager->getDefinition($entity_type)->getListCacheTags(); foreach ($event_types as $event_type) { $cache_tags = Cache::mergeTags($cache_tags, $event_type->getCacheTags()); } // Only need one set of tasks task per entity type. if ($this->routeProvider->getRouteByName("entity.{$entity_type}.canonical")) { $event_default = "rng.event.{$entity_type}.event.default"; $this->derivatives[$event_default] = array('title' => t('Event'), 'base_route' => "entity.{$entity_type}.canonical", 'route_name' => "rng.event.{$entity_type}.event", 'weight' => 30, 'cache_tags' => $cache_tags); $this->derivatives["rng.event.{$entity_type}.event.settings"] = array('title' => t('Settings'), 'route_name' => $this->derivatives[$event_default]['route_name'], 'parent_id' => 'rng.local_tasks:' . $event_default, 'weight' => 10, 'cache_tags' => $cache_tags); $this->derivatives["rng.event.{$entity_type}.event.access"] = array('title' => t('Access'), 'route_name' => "rng.event.{$entity_type}.access", 'parent_id' => 'rng.local_tasks:' . $event_default, 'weight' => 20, 'cache_tags' => $cache_tags); $this->derivatives["rng.event.{$entity_type}.event.messages"] = array('title' => t('Messages'), 'route_name' => "rng.event.{$entity_type}.messages", 'parent_id' => 'rng.local_tasks:' . $event_default, 'weight' => 30, 'cache_tags' => $cache_tags); $this->derivatives["rng.event.{$entity_type}.event.group.list"] = array('title' => t('Groups'), 'route_name' => "rng.event.{$entity_type}.group.list", 'parent_id' => 'rng.local_tasks:' . $event_default, 'weight' => 40, 'cache_tags' => $cache_tags); $this->derivatives["rng.event.{$entity_type}.register.type_list"] = array('route_name' => "rng.event.{$entity_type}.register.type_list", 'base_route' => "entity.{$entity_type}.canonical", 'title' => t('Register'), 'weight' => 40, 'cache_tags' => $cache_tags); } } foreach ($this->derivatives as &$entry) { $entry += $base_plugin_definition; } return parent::getDerivativeDefinitions($base_plugin_definition); }
/** * {@inheritdoc} * * A specific createInstance method is necessary to pass the migration on. */ public function createInstance($plugin_id, array $configuration = array(), MigrationInterface $migration = NULL) { if (substr($plugin_id, 0, 7) == 'entity:' && !$this->entityManager->getDefinition(substr($plugin_id, 7), FALSE)) { $plugin_id = 'null'; } return parent::createInstance($plugin_id, $configuration, $migration); }
/** * Creates a new NodeType instance. * * @param EntityManagerInterface $entity_manager * The entity manager. * @param array $configuration * The plugin configuration, i.e. an array with configuration values keyed * by configuration option name. The special key 'context' may be used to * initialize the defined contexts by setting it to an array of context * values keyed by context names. * @param string $plugin_id * The plugin_id for the plugin instance. * @param mixed $plugin_definition * The plugin implementation definition. */ public function __construct(EntityManagerInterface $entity_manager, array $configuration, $plugin_id, $plugin_definition) { parent::__construct($configuration, $plugin_id, $plugin_definition); $this->entityStorage = $entity_manager->getStorage($this->getDerivativeId()); $this->bundleType = $entity_manager->getDefinition($this->getDerivativeId()); $this->bundleOf = $entity_manager->getDefinition($this->bundleType->getBundleOf()); }
/** * {@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'); }
/** * {@inheritdoc} */ public function calculateDependencies() { // The empty source plugin supports the entity_type constant. if (isset($this->configuration['constants']['entity_type'])) { $this->addDependency('module', $this->entityManager->getDefinition($this->configuration['constants']['entity_type'])->getProvider()); } return $this->dependencies; }
/** * Adds form elements to list affected configuration entities. * * @param array $form * The form array to add elements to. * @param string $type * The type of dependency being checked. Either 'module', 'theme', 'config' * or 'content'. * @param array $names * The specific names to check. If $type equals 'module' or 'theme' then it * should be a list of module names or theme names. In the case of 'config' * or 'content' it should be a list of configuration dependency names. * @param \Drupal\Core\Config\ConfigManagerInterface $config_manager * The config manager. * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager * The entity manager. * * @see \Drupal\Core\Config\ConfigManagerInterface::getConfigEntitiesToChangeOnDependencyRemoval() */ protected function addDependencyListsToForm(array &$form, $type, array $names, ConfigManagerInterface $config_manager, EntityManagerInterface $entity_manager) { // Get the dependent entities. $dependent_entities = $config_manager->getConfigEntitiesToChangeOnDependencyRemoval($type, $names); $entity_types = array(); $form['entity_updates'] = array('#type' => 'details', '#title' => $this->t('Configuration updates'), '#description' => $this->t('The listed configuration will be updated.'), '#open' => TRUE, '#access' => FALSE); foreach ($dependent_entities['update'] as $entity) { /** @var \Drupal\Core\Config\Entity\ConfigEntityInterface $entity */ $entity_type_id = $entity->getEntityTypeId(); if (!isset($form['entity_updates'][$entity_type_id])) { $entity_type = $entity_manager->getDefinition($entity_type_id); // Store the ID and label to sort the entity types and entities later. $label = $entity_type->getLabel(); $entity_types[$entity_type_id] = $label; $form['entity_updates'][$entity_type_id] = array('#theme' => 'item_list', '#title' => $label, '#items' => array()); } $form['entity_updates'][$entity_type_id]['#items'][$entity->id()] = $entity->label() ?: $entity->id(); } if (!empty($dependent_entities['update'])) { $form['entity_updates']['#access'] = TRUE; // Add a weight key to the entity type sections. asort($entity_types, SORT_FLAG_CASE); $weight = 0; foreach ($entity_types as $entity_type_id => $label) { $form['entity_updates'][$entity_type_id]['#weight'] = $weight; // Sort the list of entity labels alphabetically. ksort($form['entity_updates'][$entity_type_id]['#items'], SORT_FLAG_CASE); $weight++; } } $form['entity_deletes'] = array('#type' => 'details', '#title' => $this->t('Configuration deletions'), '#description' => $this->t('The listed configuration will be deleted.'), '#open' => TRUE, '#access' => FALSE); foreach ($dependent_entities['delete'] as $entity) { $entity_type_id = $entity->getEntityTypeId(); if (!isset($form['entity_deletes'][$entity_type_id])) { $entity_type = $entity_manager->getDefinition($entity_type_id); // Store the ID and label to sort the entity types and entities later. $label = $entity_type->getLabel(); $entity_types[$entity_type_id] = $label; $form['entity_deletes'][$entity_type_id] = array('#theme' => 'item_list', '#title' => $label, '#items' => array()); } $form['entity_deletes'][$entity_type_id]['#items'][$entity->id()] = $entity->label() ?: $entity->id(); } if (!empty($dependent_entities['delete'])) { $form['entity_deletes']['#access'] = TRUE; // Add a weight key to the entity type sections. asort($entity_types, SORT_FLAG_CASE); $weight = 0; foreach ($entity_types as $entity_type_id => $label) { if (isset($form['entity_deletes'][$entity_type_id])) { $form['entity_deletes'][$entity_type_id]['#weight'] = $weight; // Sort the list of entity labels alphabetically. ksort($form['entity_deletes'][$entity_type_id]['#items'], SORT_FLAG_CASE); $weight++; } } } }
/** * {@inheritdoc} */ public function enhance(array $defaults, Request $request) { if (($bundle = $this->entityManager->getDefinition($defaults['entity_type_id'])->getBundleEntityType()) && isset($defaults[$bundle])) { // Field UI forms only need the actual name of the bundle they're dealing // with, not an upcasted entity object, so provide a simple way for them // to get it. $defaults['bundle'] = $defaults['_raw_variables']->get($bundle); } return $defaults; }
/** * {@inheritdoc} */ protected function getFormArgument(RouteMatchInterface $route_match) { $form_arg = $route_match->getRouteObject()->getDefault('_entity_wizard'); list($entity_type_id, $operation) = explode('.', $form_arg); $definition = $this->entityManager->getDefinition($entity_type_id); $handlers = $definition->getHandlerClasses(); if (empty($handlers['wizard'][$operation])) { throw new \Exception(sprintf('Unsupported wizard operation %s', $operation)); } return $handlers['wizard'][$operation]; }
/** * {@inheritdoc} * * @return \Drupal\Core\Entity\EntityInterface|array */ public function processRequest(Request $request, RouteMatchInterface $route_match, SerializerInterface $serializer) { // Unserialize the content of the request if there is any. $content = $request->getContent(); if (!empty($content)) { $entity_type_id = $this->getDerivativeId(); /** @var $entity_type \Drupal\Core\Entity\EntityTypeInterface */ $entity_type = $this->manager->getDefinition($entity_type_id); return $serializer->deserialize($content, $entity_type->getClass(), $request->getContentType(), ['entity_type' => $entity_type_id]); } return []; }
/** * {@inheritdoc} */ public function buildForm(array $form, array &$form_state, $entity_type_id = NULL, $bundle = NULL) { $entity_type = $this->entityManager->getDefinition($entity_type_id); $this->bundleEntityType = $entity_type->getBundleEntityType(); if (!isset($form_state['bundle'])) { if (!$bundle) { $bundle = $this->getRequest()->attributes->get('_raw_variables')->get($this->bundleEntityType); } $form_state['bundle'] = $bundle; } $this->entity_type = $entity_type_id; $this->bundle = $form_state['bundle']; }
/** * {@inheritdoc} */ protected function alterRoutes(RouteCollection $collection) { $event_types = $this->eventManager->getEventTypes(); foreach (array_keys($event_types) as $entity_type) { $definition = $this->entityManager->getDefinition($entity_type); if ($canonical_path = $definition->getLinkTemplate('canonical')) { $manage_requirements = ['_entity_access' => $entity_type . '.manage event', '_entity_is_event' => 'TRUE', '_permission' => 'debug rng']; $options = []; $options['parameters'][$entity_type]['type'] = 'entity:' . $entity_type; // Rules. $route = new Route($canonical_path . '/event/rules', array('_controller' => '\\Drupal\\rng_debug\\Controller\\DebugController::listing', '_title' => 'Rules', 'event' => $entity_type), $manage_requirements, $options); $collection->add("rng.event.{$entity_type}.rules", $route); } } }
/** * {@inheritdoc} */ public function denormalize($data, $class, $format = NULL, array $context = array()) { if (empty($context['entity_type'])) { throw new UnexpectedValueException('Entity type parameter must be included in context.'); } $entity_type = $this->entityManager->getDefinition($context['entity_type']); // The bundle property behaves differently from other entity properties. // i.e. the nested structure with a 'value' key does not work. if ($entity_type->hasKey('bundle')) { $bundle_key = $entity_type->getKey('bundle'); $type = $data[$bundle_key][0]['value']; $data[$bundle_key] = $type; } return $this->entityManager->getStorage($context['entity_type'])->create($data); }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state, $entity_type_id = NULL, $bundle = NULL) { $entity_type = $this->entityManager->getDefinition($entity_type_id); $this->bundleEntityType = $entity_type->getBundleEntityType(); $stored_bundle = $form_state->get('bundle'); if (!$stored_bundle) { if (!$bundle) { $bundle = $this->getRequest()->attributes->get('_raw_variables')->get($this->bundleEntityType); } $stored_bundle = $bundle; $form_state->set('bundle', $bundle); } $this->entity_type = $entity_type_id; $this->bundle = $stored_bundle; }
/** * {@inheritdoc} */ public function batchUpdate(&$context) { if (!isset($context['sandbox']['current'])) { $context['sandbox']['count'] = 0; $context['sandbox']['current'] = 0; } $entity_type = $this->entityManager->getDefinition($this->getEntityTypeId()); $id_key = $entity_type->getKey('id'); $query = db_select($entity_type->get('base_table'), 'base_table'); $query->leftJoin('url_alias', 'ua', "CONCAT('" . $this->getSourcePrefix() . "' , base_table.{$id_key}) = ua.source"); $query->addField('base_table', $id_key, 'id'); $query->isNull('ua.source'); $query->condition('base_table.' . $id_key, $context['sandbox']['current'], '>'); $query->orderBy('base_table.' . $id_key); $query->addTag('pathauto_bulk_update'); $query->addMetaData('entity', $this->getEntityTypeId()); // Get the total amount of items to process. if (!isset($context['sandbox']['total'])) { $context['sandbox']['total'] = $query->countQuery()->execute()->fetchField(); // If there are no nodes to update, the stop immediately. if (!$context['sandbox']['total']) { $context['finished'] = 1; return; } } $query->range(0, 25); $ids = $query->execute()->fetchCol(); $this->bulkUpdate($ids); $context['sandbox']['count'] += count($ids); $context['sandbox']['current'] = max($ids); $context['message'] = t('Updated alias for %label @id.', array('%label' => $entity_type->getLabel(), '@id' => end($ids))); if ($context['sandbox']['count'] != $context['sandbox']['total']) { $context['finished'] = $context['sandbox']['count'] / $context['sandbox']['total']; } }
/** * {@inheritdoc} */ public function applyUpdates() { foreach ($this->getChangeList() as $entity_type_id => $change_list) { // Process entity type definition changes. if (!empty($change_list['entity_type']) && $change_list['entity_type'] == static::DEFINITION_UPDATED) { $entity_type = $this->entityManager->getDefinition($entity_type_id); $original = $this->entityManager->getLastInstalledDefinition($entity_type_id); $this->entityManager->onEntityTypeUpdate($entity_type, $original); } // Process field storage definition changes. if (!empty($change_list['field_storage_definitions'])) { $storage_definitions = $this->entityManager->getFieldStorageDefinitions($entity_type_id); $original_storage_definitions = $this->entityManager->getLastInstalledFieldStorageDefinitions($entity_type_id); foreach ($change_list['field_storage_definitions'] as $field_name => $change) { switch ($change) { case static::DEFINITION_CREATED: $this->entityManager->onFieldStorageDefinitionCreate($storage_definitions[$field_name]); break; case static::DEFINITION_UPDATED: $this->entityManager->onFieldStorageDefinitionUpdate($storage_definitions[$field_name], $original_storage_definitions[$field_name]); break; case static::DEFINITION_DELETED: $this->entityManager->onFieldStorageDefinitionDelete($original_storage_definitions[$field_name]); break; } } } } }
/** * Tests that views are disabled when an entity type is deleted. */ public function testDeleteEntityType() { $entity_storage = $this->entityManager->getStorage('view'); $views = $entity_storage->loadMultiple(); // Ensure that all test views exists. $this->assertTrue(isset($views['test_view_entity_test'])); $this->assertTrue(isset($views['test_view_entity_test_revision'])); $this->assertTrue(isset($views['test_view_entity_test_data'])); $this->assertTrue(isset($views['test_view_entity_test_additional_base_field'])); $event = new EntityTypeEvent($this->entityManager->getDefinition('entity_test_update')); $this->eventDispatcher->dispatch(EntityTypeEvents::DELETE, $event); // We expect that views which use 'entity_test_update' as base tables are // disabled. $views = $entity_storage->loadMultiple(); // Ensure that all test views still exists after the deletion of the // entity type. $this->assertTrue(isset($views['test_view_entity_test'])); $this->assertTrue(isset($views['test_view_entity_test_revision'])); $this->assertTrue(isset($views['test_view_entity_test_data'])); $this->assertTrue(isset($views['test_view_entity_test_additional_base_field'])); // Ensure that they are all disabled. $this->assertFalse($views['test_view_entity_test']->status()); $this->assertFalse($views['test_view_entity_test_revision']->status()); $this->assertFalse($views['test_view_entity_test_data']->status()); $this->assertFalse($views['test_view_entity_test_additional_base_field']->status()); }
/** * Builds an EntityQuery to get entities. * * @param $match * Text to match the label against. * * @return \Drupal\Core\Entity\Query\QueryInterface * The EntityQuery object with the basic conditions and sorting applied to * it. */ protected function buildEntityQuery($match) { $match = $this->database->escapeLike($match); $entity_type = $this->entityManager->getDefinition($this->target_type); $query = $this->entityManager->getStorage($this->target_type)->getQuery(); $label_key = $entity_type->getKey('label'); if ($label_key) { $query->condition($label_key, '%' . $match . '%', 'LIKE'); $query->sort($label_key, 'ASC'); } // Bundle check. if (!empty($this->configuration['bundles']) && $bundle_key = $entity_type->getKey('bundle')) { $query->condition($bundle_key, $this->configuration['bundles'], 'IN'); } // Add tags to let other modules alter the query. $query->addTag('linkit_entity_autocomplete'); $query->addTag('linkit_entity_' . $this->target_type . '_autocomplete'); // Add access tag for the query. $query->addTag('entity_access'); $query->addTag($this->target_type . '_access'); return $query; }
/** * 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'; } }
/** * {@inheritdoc} */ public function tableFields($bundles) { $info = $this->entityManager->getDefinition($this->entityTypeId()); $definitions = $this->entityManager->getBaseFieldDefinitions($this->entityTypeId()); $label_key = $info->getKey('label'); $label_field_label = t('Label'); if ($label_key && isset($definitions[$label_key])) { $label_field_label = $definitions[$label_key]->getLabel(); } $bundle_key = $info->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, ]; } return $fields; }
/** * Builds an EntityQuery to get referenceable entities. * * @param string|null $match * (Optional) Text to match the label against. Defaults to NULL. * @param string $match_operator * (Optional) The operation the matching should be done with. Defaults * to "CONTAINS". * * @return \Drupal\Core\Entity\Query\QueryInterface * The EntityQuery object with the basic conditions and sorting applied to * it. */ protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') { $target_type = $this->configuration['target_type']; $handler_settings = $this->configuration['handler_settings']; $entity_type = $this->entityManager->getDefinition($target_type); $query = $this->entityManager->getStorage($target_type)->getQuery(); if (!empty($handler_settings['target_bundles'])) { $query->condition($entity_type->getKey('bundle'), $handler_settings['target_bundles'], 'IN'); } if (isset($match) && ($label_key = $entity_type->getKey('label'))) { $query->condition($label_key, $match, $match_operator); } // Add entity-access tag. $query->addTag($target_type . '_access'); // Add the Selection handler for // entity_reference_query_entity_reference_alter(). $query->addTag('entity_reference'); $query->addMetaData('entity_reference_selection_handler', $this); // Add the sort option. if (!empty($handler_settings['sort'])) { $sort_settings = $handler_settings['sort']; if ($sort_settings['field'] != '_none') { $query->sort($sort_settings['field'], $sort_settings['direction']); } } return $query; }
/** * Helper function for generating label and id form elements. * * @param array $form * @param \Drupal\Core\Form\FormStateInterface $form_state * * @return array */ protected function customizeForm(array $form, FormStateInterface $form_state) { $form = parent::customizeForm($form, $form_state); if ($this->machine_name) { $entity = $this->entityManager->getStorage($this->getEntityType())->load($this->machine_name); } else { $entity = NULL; } // If the entity already exists, allow for non-linear step interaction. if ($entity) { // Setup the step rendering theme element. $prefix = ['#theme' => ['ctools_wizard_trail_links'], '#wizard' => $this]; $form['#prefix'] = \Drupal::service('renderer')->render($prefix); } $cached_values = $form_state->getTemporaryValue('wizard'); // Get the current form operation. $operation = $this->getOperation($cached_values); $operations = $this->getOperations(); $default_operation = reset($operations); if ($operation['form'] == $default_operation['form']) { // Get the plugin definition of this entity. $definition = $this->entityManager->getDefinition($this->getEntityType()); // Create id and label form elements. $form['name'] = array('#type' => 'fieldset', '#attributes' => array('class' => array('fieldset-no-legend')), '#title' => $this->getWizardLabel()); $form['name']['label'] = array('#type' => 'textfield', '#title' => $this->getMachineLabel(), '#required' => TRUE, '#size' => 32, '#default_value' => !empty($cached_values['label']) ? $cached_values['label'] : '', '#maxlength' => 255, '#disabled' => !empty($cached_values['label'])); $form['name']['id'] = array('#type' => 'machine_name', '#maxlength' => 128, '#machine_name' => array('source' => array('name', 'label'), 'exists' => $this->exists()), '#description' => $this->t('A unique machine-readable name for this !entity_type. It must only contain lowercase letters, numbers, and underscores.', ['!entity_type' => $definition->getLabel()]), '#default_value' => !empty($cached_values['id']) ? $cached_values['id'] : '', '#disabled' => !empty($cached_values['id'])); } return $form; }
/** * Builds an EntityQuery to get referenceable entities. * * @param string|null $match * (Optional) Text to match the label against. Defaults to NULL. * @param string $match_operator * (Optional) The operation the matching should be done with. Defaults * to "CONTAINS". * * @return \Drupal\Core\Entity\Query\QueryInterface * The EntityQuery object with the basic conditions and sorting applied to * it. */ protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') { $target_type = $this->configuration['target_type']; $handler_settings = $this->configuration['handler_settings']; $entity_type = $this->entityManager->getDefinition($target_type); $query = $this->entityManager->getStorage($target_type)->getQuery(); // If 'target_bundles' is NULL, all bundles are referenceable, no further // conditions are needed. if (isset($handler_settings['target_bundles']) && is_array($handler_settings['target_bundles'])) { // If 'target_bundles' is an empty array, no bundle is referenceable, // force the query to never return anything and bail out early. if ($handler_settings['target_bundles'] === []) { $query->condition($entity_type->getKey('id'), NULL, '='); return $query; } else { $query->condition($entity_type->getKey('bundle'), $handler_settings['target_bundles'], 'IN'); } } if (isset($match) && ($label_key = $entity_type->getKey('label'))) { $query->condition($label_key, $match, $match_operator); } // Add entity-access tag. $query->addTag($target_type . '_access'); // Add the Selection handler for system_query_entity_reference_alter(). $query->addTag('entity_reference'); $query->addMetaData('entity_reference_selection_handler', $this); // Add the sort option. if (!empty($handler_settings['sort'])) { $sort_settings = $handler_settings['sort']; if ($sort_settings['field'] != '_none') { $query->sort($sort_settings['field'], $sort_settings['direction']); } } return $query; }
/** * Gets the entity schema for the specified entity type. * * Entity types may override this method in order to optimize the generated * schema of the entity tables. However, only cross-field optimizations should * be added here; e.g., an index spanning multiple fields. Optimizations that * apply to a single field have to be added via * SqlContentEntityStorageSchema::getSharedTableFieldSchema() instead. * * @param \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type * The entity type definition. * @param bool $reset * (optional) If set to TRUE static cache will be ignored and a new schema * array generation will be performed. Defaults to FALSE. * * @return array * A Schema API array describing the entity schema, excluding dedicated * field tables. * * @throws \Drupal\Core\Field\FieldException */ protected function getEntitySchema(ContentEntityTypeInterface $entity_type, $reset = FALSE) { $this->checkEntityType($entity_type); $entity_type_id = $entity_type->id(); if (!isset($this->schema[$entity_type_id]) || $reset) { // Back up the storage definition and replace it with the passed one. // @todo Instead of switching the wrapped entity type, we should be able // to instantiate a new table mapping for each entity type definition. // See https://www.drupal.org/node/2274017. $actual_definition = $this->entityManager->getDefinition($entity_type_id); $this->storage->setEntityType($entity_type); // Prepare basic information about the entity type. $tables = $this->getEntitySchemaTables(); // Initialize the table schema. $schema[$tables['base_table']] = $this->initializeBaseTable($entity_type); if (isset($tables['revision_table'])) { $schema[$tables['revision_table']] = $this->initializeRevisionTable($entity_type); } if (isset($tables['data_table'])) { $schema[$tables['data_table']] = $this->initializeDataTable($entity_type); } if (isset($tables['revision_data_table'])) { $schema[$tables['revision_data_table']] = $this->initializeRevisionDataTable($entity_type); } // We need to act only on shared entity schema tables. $table_mapping = $this->storage->getTableMapping(); $table_names = array_diff($table_mapping->getTableNames(), $table_mapping->getDedicatedTableNames()); $storage_definitions = $this->entityManager->getFieldStorageDefinitions($entity_type_id); foreach ($table_names as $table_name) { if (!isset($schema[$table_name])) { $schema[$table_name] = array(); } foreach ($table_mapping->getFieldNames($table_name) as $field_name) { if (!isset($storage_definitions[$field_name])) { throw new FieldException("Field storage definition for '{$field_name}' could not be found."); } elseif ($table_mapping->allowsSharedTableStorage($storage_definitions[$field_name])) { $column_names = $table_mapping->getColumnNames($field_name); $storage_definition = $storage_definitions[$field_name]; $schema[$table_name] = array_merge_recursive($schema[$table_name], $this->getSharedTableFieldSchema($storage_definition, $table_name, $column_names)); } } } // Process tables after having gathered field information. $this->processBaseTable($entity_type, $schema[$tables['base_table']]); if (isset($tables['revision_table'])) { $this->processRevisionTable($entity_type, $schema[$tables['revision_table']]); } if (isset($tables['data_table'])) { $this->processDataTable($entity_type, $schema[$tables['data_table']]); } if (isset($tables['revision_data_table'])) { $this->processRevisionDataTable($entity_type, $schema[$tables['revision_data_table']]); } $this->schema[$entity_type_id] = $schema; // Restore the actual definition. $this->storage->setEntityType($actual_definition); } return $this->schema[$entity_type_id]; }
/** * {@inheritdoc} */ public function assignConfigPackage($package_name, array $item_names, $force = FALSE) { $config_collection = $this->getConfigCollection(); $module_list = $this->moduleHandler->getModuleList(); $packages =& $this->packages; if (isset($packages[$package_name])) { $package =& $packages[$package_name]; } else { throw new \Exception($this->t('Failed to package @package_name. Package not found.', ['@package_name' => $package_name])); } foreach ($item_names as $item_name) { if (isset($config_collection[$item_name])) { // Add to the package if: // - force is set or // - the item hasn't already been assigned elsewhere, and // - the package hasn't been excluded. // - and the item isn't already in the package. // Determine if the item is provided by an extension. $extension_provided = $config_collection[$item_name]->isExtensionProvided() === TRUE; $already_assigned = !empty($config_collection[$item_name]->getPackage()); // If this is the profile package, we can reassign extension-provided configuration. $is_profile_package = $this->getAssigner()->getBundle($package->getBundle())->isProfilePackage($package->getMachineName()); // An item is assignable if: // - it is not extension provided or this is the profile package, and // - it is not flagged as excluded. $assignable = (!$extension_provided || $is_profile_package) && !$config_collection[$item_name]->isExcluded(); $excluded_from_package = in_array($package_name, $config_collection[$item_name]->getPackageExcluded()); $already_in_package = in_array($item_name, $package->getConfig()); if (($force || !$already_assigned && $assignable && !$excluded_from_package) && !$already_in_package) { // Add the item to the package's config array. $package->appendConfig($item_name); // Mark the item as already assigned. $config_collection[$item_name]->setPackage($package_name); $module_dependencies = []; // Add a dependency on the extension that provides this configuration // type. if ($config_collection[$item_name]->getType() != static::SYSTEM_SIMPLE_CONFIG) { $provider = $this->entityManager->getDefinition($config_collection[$item_name]->getType())->getProvider(); // Ensure the provider is an installed module and not, for example, // 'core'. if (isset($module_list[$provider])) { $module_dependencies[] = $provider; } } // For configuration in the InstallStorage::CONFIG_INSTALL_DIRECTORY // directory, set any module dependencies of the configuration item // as package dependencies. // As its name implies, the core-provided // InstallStorage::CONFIG_OPTIONAL_DIRECTORY should not create // dependencies. if ($config_collection[$item_name]->getSubdirectory() === InstallStorage::CONFIG_INSTALL_DIRECTORY && isset($config_collection[$item_name]->getData()['dependencies']['module'])) { $module_dependencies = array_merge($module_dependencies, $config_collection[$item_name]->getData()['dependencies']['module']); } $package->setDependencies($this->mergeUniqueItems($package->getDependencies(), $module_dependencies)); } } } $this->setConfigCollection($config_collection); }
/** * Constructs an EntityProcessorBase object. * * @param array $configuration * The plugin configuration. * @param string $plugin_id * The plugin id. * @param array $plugin_definition * The plugin definition. * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager * The entity manager. * @param \Drupal\Core\Entity\Query\QueryFactory $query_factory * The entity query factory. */ public function __construct(array $configuration, $plugin_id, array $plugin_definition, EntityManagerInterface $entity_manager, QueryFactory $query_factory) { $this->entityManager = $entity_manager; $this->entityType = $entity_manager->getDefinition($plugin_definition['entity_type']); $this->storageController = $entity_manager->getStorage($plugin_definition['entity_type']); $this->queryFactory = $query_factory; parent::__construct($configuration, $plugin_id, $plugin_definition); }