/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $forum_config = $this->config('forum.settings'); $vid = $forum_config->get('vocabulary'); $vocabulary = $this->entityManager->getStorage('taxonomy_vocabulary')->load($vid); if (!$vocabulary) { throw new NotFoundHttpException(); } // Build base taxonomy term overview. $form = parent::buildForm($form, $form_state, $vocabulary); foreach (Element::children($form['terms']) as $key) { if (isset($form['terms'][$key]['#term'])) { $term = $form['terms'][$key]['#term']; $form['terms'][$key]['term']['#url'] = Url::fromRoute('forum.page', ['taxonomy_term' => $term->id()]); unset($form['terms'][$key]['operations']['#links']['delete']); $route_parameters = $form['terms'][$key]['operations']['#links']['edit']['url']->getRouteParameters(); if (!empty($term->forum_container->value)) { $form['terms'][$key]['operations']['#links']['edit']['title'] = $this->t('edit container'); $form['terms'][$key]['operations']['#links']['edit']['url'] = Url::fromRoute('entity.taxonomy_term.forum_edit_container_form', $route_parameters); } else { $form['terms'][$key]['operations']['#links']['edit']['title'] = $this->t('edit forum'); $form['terms'][$key]['operations']['#links']['edit']['url'] = Url::fromRoute('entity.taxonomy_term.forum_edit_form', $route_parameters); } // We don't want the redirect from the link so we can redirect the // delete action. unset($form['terms'][$key]['operations']['#links']['edit']['query']['destination']); } } // Remove the alphabetical reset. unset($form['actions']['reset_alphabetical']); // Use the existing taxonomy overview submit handler. $form['terms']['#empty'] = $this->t('No containers or forums available. <a href="@container">Add container</a> or <a href="@forum">Add forum</a>.', array('@container' => $this->url('forum.add_container'), '@forum' => $this->url('forum.add_forum'))); return $form; }
/** * {@inheritdoc} */ public function process($text, $langcode) { $result = new FilterProcessResult($text); if (stristr($text, 'data-entity-type="file"') !== FALSE) { $dom = Html::load($text); $xpath = new \DOMXPath($dom); $processed_uuids = array(); foreach ($xpath->query('//*[@data-entity-type="file" and @data-entity-uuid]') as $node) { $uuid = $node->getAttribute('data-entity-uuid'); // If there is a 'src' attribute, set it to the file entity's current // URL. This ensures the URL works even after the file location changes. if ($node->hasAttribute('src')) { $file = $this->entityManager->loadEntityByUuid('file', $uuid); if ($file) { $node->setAttribute('src', file_url_transform_relative(file_create_url($file->getFileUri()))); } } // Only process the first occurrence of each file UUID. if (!isset($processed_uuids[$uuid])) { $processed_uuids[$uuid] = TRUE; $file = $this->entityManager->loadEntityByUuid('file', $uuid); if ($file) { $result->addCacheTags($file->getCacheTags()); } } } $result->setProcessedText(Html::serialize($dom)); } return $result; }
/** * Creates a NodeBlock instance. * * @param array $configuration * @param string $plugin_id * @param mixed $plugin_definition * @param EntityManagerInterface $entity_manager */ public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityManagerInterface $entity_manager) { parent::__construct($configuration, $plugin_id, $plugin_definition); $this->viewBuilder = $entity_manager->getViewBuilder('node'); $this->nodeStorage = $entity_manager->getStorage('node'); $this->node = $entity_manager->getStorage('node')->load($this->getDerivativeId()); }
/** * Handles the response for inline entity form autocompletion. * * @return \Symfony\Component\HttpFoundation\JsonResponse */ public function autocomplete($entity_type_id, $field_name, $bundle, Request $request) { $string = $request->query->get('q'); $fields = $this->entityManager->getFieldDefinitions($entity_type_id, $bundle); $widget = $this->entityManager->getStorage('entity_form_display')->load($entity_type_id . '.' . $bundle . '.default')->getComponent($field_name); // The path was passed invalid parameters, or the string is empty. // strlen() is used instead of empty() since '0' is a valid value. if (!isset($fields[$field_name]) || !$widget || !strlen($string)) { throw new AccessDeniedHttpException(); } $field = $fields[$field_name]; $results = array(); if ($field->getType() == 'entity_reference') { /** @var \Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface $handler */ $handler = $this->selectionManager->getSelectionHandler($field); $entity_labels = $handler->getReferenceableEntities($string, $widget['settings']['match_operator'], 10); foreach ($entity_labels as $bundle => $labels) { // Loop through each entity type, and autocomplete with its titles. foreach ($labels as $entity_id => $label) { // entityreference has already check_plain-ed the title. $results[] = t('!label (!entity_id)', array('!label' => $label, '!entity_id' => $entity_id)); } } } $matches = array(); foreach ($results as $result) { // Strip things like starting/trailing white spaces, line breaks and tags. $key = preg_replace('/\\s\\s+/', ' ', str_replace("\n", '', trim(Html::decodeEntities(strip_tags($result))))); $matches[] = ['value' => $key, 'label' => '<div class="reference-autocomplete">' . $result . '</div>']; } return new JsonResponse($matches); }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $form = parent::buildForm($form, $form_state); /** @var \Drupal\rng\EventTypeInterface $event_type */ $event_type = $this->entity; if (!$event_type->isNew()) { $form['#title'] = $this->t('Edit event type %label configuration', array('%label' => $event_type->label())); } if ($event_type->isNew()) { $bundle_options = []; // Generate a list of fieldable bundles which are not events. foreach ($this->entityManager->getDefinitions() as $entity_type) { if ($entity_type->isSubclassOf('\\Drupal\\Core\\Entity\\ContentEntityInterface')) { foreach ($this->entityManager->getBundleInfo($entity_type->id()) as $bundle => $bundle_info) { if (!$this->eventManager->eventType($entity_type->id(), $bundle)) { $bundle_options[(string) $entity_type->getLabel()][$entity_type->id() . '.' . $bundle] = $bundle_info['label']; } } } } if ($this->moduleHandler->moduleExists('node')) { $form['#attached']['library'][] = 'rng/rng.admin'; $form['entity_type'] = ['#type' => 'radios', '#options' => NULL, '#title' => $this->t('Event entity type'), '#required' => TRUE]; $form['entity_type']['node']['radio'] = ['#type' => 'radio', '#title' => $this->t('Create a new content type'), '#description' => $this->t('Create a content type to use as an event type.'), '#return_value' => "node", '#parents' => array('entity_type'), '#default_value' => 'node']; $form['entity_type']['existing']['radio'] = ['#type' => 'radio', '#title' => $this->t('Use existing bundle'), '#description' => $this->t('Use an existing entity/bundle combination.'), '#return_value' => "existing", '#parents' => array('entity_type'), '#default_value' => '']; $form['entity_type']['existing']['container'] = ['#type' => 'container', '#attributes' => ['class' => ['rng-radio-indent']]]; } $form['entity_type']['existing']['container']['bundle'] = array('#type' => 'select', '#title' => $this->t('Bundle'), '#options' => $bundle_options, '#default_value' => $event_type->id(), '#disabled' => !$event_type->isNew(), '#empty_option' => $bundle_options ? NULL : t('No Bundles Available')); } $form['settings'] = array('#type' => 'fieldset', '#title' => $this->t('Settings')); // Mirror permission. $form['access']['mirror_update'] = array('#group' => 'settings', '#type' => 'checkbox', '#title' => t('Mirror manage registrations with update permission'), '#description' => t('Allow users to <strong>manage registrations</strong> if they have <strong>update</strong> permission on an event entity.'), '#default_value' => (bool) ($event_type->getEventManageOperation() !== NULL ? $event_type->getEventManageOperation() : TRUE)); return $form; }
/** * {@inheritdoc} */ public function build(RouteMatchInterface $route_match) { $breadcrumb = new Breadcrumb(); $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>')); $term = $route_match->getParameter('taxonomy_term'); // Breadcrumb needs to have terms cacheable metadata as a cacheable // dependency even though it is not shown in the breadcrumb because e.g. its // parent might have changed. $breadcrumb->addCacheableDependency($term); // @todo This overrides any other possible breadcrumb and is a pure // hard-coded presumption. Make this behavior configurable per // vocabulary or term. $parents = $this->termStorage->loadAllParents($term->id()); // Remove current term being accessed. array_shift($parents); foreach (array_reverse($parents) as $term) { $term = $this->entityManager->getTranslationFromContext($term); $breadcrumb->addCacheableDependency($term); $breadcrumb->addLink(Link::createFromRoute($term->getName(), 'entity.taxonomy_term.canonical', array('taxonomy_term' => $term->id()))); } // This breadcrumb builder is based on a route parameter, and hence it // depends on the 'route' cache context. $breadcrumb->addCacheContexts(['route']); return $breadcrumb; }
/** * {@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} * * @covers ::__construct */ protected function setUp() { $this->pageStorage = $this->prophesize(ConfigEntityStorageInterface::class); $this->entityManager = $this->prophesize(EntityManagerInterface::class); $this->entityManager->getStorage('page')->willReturn($this->pageStorage); $this->routeSubscriber = new PageManagerRoutes($this->entityManager->reveal()); }
/** * Returns matched labels based on a given field, instance and search string. * * This function can be used by other modules that wish to pass a mocked * definition of the field on instance. * * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition * The field definition. * @param string $entity_type * The entity type. * @param string $bundle * The entity bundle. * @param string $entity_id * (optional) The entity ID the entity reference field is attached to. * Defaults to ''. * @param string $prefix * (optional) A prefix for all the keys returned by this function. * @param string $string * (optional) The label of the entity to query by. * * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException * Thrown when the current user doesn't have access to the specifies entity. * * @return array * A list of matched entity labels. * * @see \Drupal\entity_reference\EntityReferenceController */ public function getMatches(FieldDefinitionInterface $field_definition, $entity_type, $bundle, $entity_id = '', $prefix = '', $string = '') { $matches = array(); $entity = NULL; if ($entity_id !== 'NULL') { $entity = $this->entityManager->getStorage($entity_type)->load($entity_id); if (!$entity || !$entity->access('view')) { throw new AccessDeniedHttpException(); } } $handler = $this->selectionHandlerManager->getSelectionHandler($field_definition, $entity); if (isset($string)) { // Get an array of matching entities. $widget = entity_get_form_display($entity_type, $bundle, 'default')->getComponent($field_definition->getName()); $match_operator = !empty($widget['settings']['match_operator']) ? $widget['settings']['match_operator'] : 'CONTAINS'; $entity_labels = $handler->getReferenceableEntities($string, $match_operator, 10); // Loop through the entities and convert them into autocomplete output. foreach ($entity_labels as $values) { foreach ($values as $entity_id => $label) { $key = "{$label} ({$entity_id})"; // Strip things like starting/trailing white spaces, line breaks and // tags. $key = preg_replace('/\\s\\s+/', ' ', str_replace("\n", '', trim(decode_entities(strip_tags($key))))); // Names containing commas or quotes must be wrapped in quotes. $key = Tags::encode($key); $matches[] = array('value' => $prefix . $key, 'label' => $label); } } } return $matches; }
/** * Adds content entity types checkboxes. */ protected function setContentTypeSelect(&$form, $defaults, $type, $exclude_has_config_bundles = TRUE) { $entity_types = $this->entityManager->getDefinitions(); $has_config_bundle = array(); foreach ($entity_types as $definition) { if ($entity_type_id = $definition->getBundleOf()) { $has_config_bundle[] = $entity_type_id; } } $options = array(); foreach ($entity_types as $entity_type_id => $entity_type) { if (!$entity_type instanceof ContentEntityTypeInterface) { continue; } if ($exclude_has_config_bundles && in_array($entity_type_id, $has_config_bundle)) { continue; } $options[$entity_type_id] = $entity_type->getLabel() ?: $entity_type_id; } // Sort the entity types by label. uasort($options, 'strnatcasecmp'); if (!isset($form['types'])) { $form['types'] = array('#type' => 'container', '#tree' => TRUE); } $form['types']['content'] = array('#type' => 'checkboxes', '#title' => $this->t('Content entity types'), '#description' => $this->t('Select content entity types that should be considered @type types.', array('@type' => $type)), '#options' => $options, '#default_value' => $defaults); }
/** * Constructs a SystemManager object. * * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler * The module handler. * @param \Drupal\Core\Database\Connection $database * The database connection. * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager * The entity manager. * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack * The request stack. */ public function __construct(ModuleHandlerInterface $module_handler, Connection $database, EntityManagerInterface $entity_manager, RequestStack $request_stack) { $this->moduleHandler = $module_handler; $this->database = $database; $this->menuLinkStorage = $entity_manager->getStorage('menu_link'); $this->requestStack = $request_stack; }
/** * @covers ::createPayment */ public function testCreatePayment() { $bundle = $this->randomMachineName(); $currency_code = $this->randomMachineName(); $entity_type_id = $this->randomMachineName(); $field_name = $this->randomMachineName(); $payment_type = $this->getMockBuilder(PaymentReference::class)->disableOriginalConstructor()->getMock(); $payment_type->expects($this->once())->method('setBundle')->with($bundle); $payment_type->expects($this->once())->method('setEntityTypeId')->with($entity_type_id); $payment_type->expects($this->once())->method('setFieldName')->with($field_name); $payment = $this->getMock(PaymentInterface::class); $payment->expects($this->once())->method('setCurrencyCode')->with($currency_code); $payment->expects($this->once())->method('getPaymentType')->willReturn($payment_type); $payment_storage = $this->getMock(EntityStorageInterface::class); $payment_storage->expects($this->once())->method('create')->with(array('bundle' => 'payment_reference'))->willReturn($payment); $this->entityManager->expects($this->once())->method('getStorage')->with('payment')->willReturn($payment_storage); $line_item_a = $this->getMock(PaymentLineItemInterface::class); $line_item_plugin_id_a = $this->randomMachineName(); $line_item_plugin_configuration_a = array('foo' => $this->randomMachineName()); $line_item_b = $this->getMock(PaymentLineItemInterface::class); $line_item_plugin_id_b = $this->randomMachineName(); $line_item_plugin_configuration_b = array('bar' => $this->randomMachineName()); $field_storage_definition = $this->getMock(FieldStorageDefinitionInterface::class); $field_storage_definition->expects($this->once())->method('getTargetEntityTypeId')->willReturn($entity_type_id); $field_definition = $this->getMock(FieldDefinitionInterface::class); $field_definition->expects($this->once())->method('getTargetBundle')->willReturn($bundle); $field_definition->expects($this->once())->method('getFieldStorageDefinition')->willReturn($field_storage_definition); $field_definition->expects($this->once())->method('getName')->willreturn($field_name); $map = array(array('currency_code', $currency_code), array('line_items_data', array(array('plugin_configuration' => $line_item_plugin_configuration_a, 'plugin_id' => $line_item_plugin_id_a), array('plugin_configuration' => $line_item_plugin_configuration_b, 'plugin_id' => $line_item_plugin_id_b)))); $field_definition->expects($this->exactly(2))->method('getSetting')->willReturnMap($map); $this->paymentLineItemManager->expects($this->at(0))->method('createInstance')->with($line_item_plugin_id_a, $line_item_plugin_configuration_a)->willReturn($line_item_a); $this->paymentLineItemManager->expects($this->at(1))->method('createInstance')->with($line_item_plugin_id_b, $line_item_plugin_configuration_b)->willReturn($line_item_b); $this->assertSame($payment, $this->sut->createPayment($field_definition)); }
/** * Returns an array of route objects. * * @return \Symfony\Component\Routing\Route[] * An array of route objects. */ public function routes() { $routes = array(); $is_multilingual = $this->languageManager->isMultilingual(); /* @var $search_api_page \Drupal\search_api_page\SearchApiPageInterface */ foreach ($this->entityManager->getStorage('search_api_page')->loadMultiple() as $search_api_page) { // Default path. $default_path = $search_api_page->getPath(); // Loop over all languages so we can get the translated path (if any). foreach ($this->languageManager->getLanguages() as $language) { // Check if we are multilingual or not. if ($is_multilingual) { $path = $this->languageManager->getLanguageConfigOverride($language->getId(), 'search_api_page.search_api_page.' . $search_api_page->id())->get('path'); } if (empty($path)) { $path = $default_path; } $args = ['_controller' => 'Drupal\\search_api_page\\Controller\\SearchApiPageController::page', 'search_api_page_name' => $search_api_page->id()]; // Use clean urls or not. if ($search_api_page->getCleanUrl()) { $path .= '/{keys}'; $args['keys'] = ''; } $routes['search_api_page.' . $language->getId() . '.' . $search_api_page->id()] = new Route($path, $args, array('_permission' => 'view search api pages')); } } return $routes; }
/** * Constructs a EmailAction object. * * @param array $configuration * A configuration array containing information about the plugin instance. * @param string $plugin_id * The plugin ID for the plugin instance. * @param mixed $plugin_definition * The plugin implementation definition. * @param \Drupal\Core\Utility\Token $token * The token service. * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager * The entity manager. * @param \Psr\Log\LoggerInterface $logger * A logger instance. */ public function __construct(array $configuration, $plugin_id, $plugin_definition, Token $token, EntityManagerInterface $entity_manager, LoggerInterface $logger) { parent::__construct($configuration, $plugin_id, $plugin_definition); $this->token = $token; $this->storage = $entity_manager->getStorage('user'); $this->logger = $logger; }
/** * Constructs a new ForumUninstallValidator. * * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager * The entity manager. * @param \Drupal\Core\Entity\Query\QueryFactory $query_factory * The entity query factory. * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory * The config factory. * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation * The string translation service. */ public function __construct(EntityManagerInterface $entity_manager, QueryFactory $query_factory, ConfigFactoryInterface $config_factory, TranslationInterface $string_translation) { $this->vocabularyStorage = $entity_manager->getStorage('taxonomy_vocabulary'); $this->queryFactory = $query_factory; $this->configFactory = $config_factory; $this->stringTranslation = $string_translation; }
/** * {@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; }
/** * 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; }
/** * 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(); }
/** * Returns an array of content translation permissions. * * @return array */ public function contentPermissions() { $permission = []; // Create a translate permission for each enabled entity type and (optionally) // bundle. foreach ($this->entityManager->getDefinitions() as $entity_type_id => $entity_type) { if ($permission_granularity = $entity_type->getPermissionGranularity()) { $t_args = ['@entity_label' => $entity_type->getLowercaseLabel()]; switch ($permission_granularity) { case 'bundle': foreach ($this->entityManager->getBundleInfo($entity_type_id) as $bundle => $bundle_info) { if ($this->contentTranslationManager->isEnabled($entity_type_id, $bundle)) { $t_args['%bundle_label'] = isset($bundle_info['label']) ? $bundle_info['label'] : $bundle; $permission["translate {$bundle} {$entity_type_id}"] = ['title' => $this->t('Translate %bundle_label @entity_label', $t_args)]; } } break; case 'entity_type': if ($this->contentTranslationManager->isEnabled($entity_type_id)) { $permission["translate {$entity_type_id}"] = ['title' => $this->t('Translate @entity_label', $t_args)]; } break; } } } return $permission; }
/** * {@inheritdoc} */ public function build(RouteMatchInterface $route_match) { $breadcrumb[] = Link::createFromRoute($this->t('Home'), '<front>'); $vocabulary = $this->entityManager->getStorage('taxonomy_vocabulary')->load($this->config->get('vocabulary')); $breadcrumb[] = Link::createFromRoute($vocabulary->label(), 'forum.index'); return $breadcrumb; }
/** * {@inheritdoc} */ public function collect(Request $request, Response $response, \Exception $exception = NULL) { $views = $this->view_executable_factory->getViews(); $storage = $this->entityManager->getStorage('view'); /** @var TraceableViewExecutable $view */ foreach ($views as $view) { if ($view->executed) { $data = ['id' => $view->storage->id(), 'current_display' => $view->current_display, 'build_time' => $view->getBuildTime(), 'execute_time' => $view->getExecuteTime(), 'render_time' => $view->getRenderTime()]; $entity = $storage->load($view->storage->id()); if ($entity->hasLinkTemplate('edit-display-form')) { $route = $entity->urlInfo('edit-display-form'); $route->setRouteParameter('display_id', $view->current_display); $data['route'] = $route->toString(); } $this->data['views'][] = $data; } } // TODO: also use those data. // $loaded = $this->entityManager->getLoaded('view'); // // if ($loaded) { // /** @var \Drupal\webprofiler\Entity\EntityStorageDecorator $views */ // foreach ($loaded->getEntities() as $views) { // $this->data['views'][] = array( // 'id' => $views->get('id'), // ); // } // } }
/** * {@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); }
/** * Checks translation access for the entity and operation on the given route. * * @param \Symfony\Component\Routing\Route $route * The route to check against. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * The parametrized route. * @param \Drupal\Core\Session\AccountInterface $account * The currently logged in account. * @param string $source * (optional) For a create operation, the language code of the source. * @param string $target * (optional) For a create operation, the language code of the translation. * @param string $language * (optional) For an update or delete operation, the language code of the * translation being updated or deleted. * @param string $entity_type_id * (optional) The entity type ID. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */ public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account, $source = NULL, $target = NULL, $language = NULL, $entity_type_id = NULL) { /* @var \Drupal\Core\Entity\ContentEntityInterface $entity */ if ($entity = $route_match->getParameter($entity_type_id)) { if ($account->hasPermission('translate any entity')) { return AccessResult::allowed()->cachePerRole(); } $operation = $route->getRequirement('_access_content_translation_manage'); /* @var \Drupal\content_translation\ContentTranslationHandlerInterface $handler */ $handler = $this->entityManager->getHandler($entity->getEntityTypeId(), 'translation'); // Load translation. $translations = $entity->getTranslationLanguages(); $languages = $this->languageManager->getLanguages(); switch ($operation) { case 'create': $source_language = $this->languageManager->getLanguage($source) ?: $entity->language(); $target_language = $this->languageManager->getLanguage($target) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT); $is_new_translation = $source_language->getId() != $target_language->getId() && isset($languages[$source_language->getId()]) && isset($languages[$target_language->getId()]) && !isset($translations[$target_language->getId()]); return AccessResult::allowedIf($is_new_translation)->cachePerRole()->cacheUntilEntityChanges($entity)->andIf($handler->getTranslationAccess($entity, $operation)); case 'update': case 'delete': $language = $this->languageManager->getLanguage($language) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT); $has_translation = isset($languages[$language->getId()]) && $language->getId() != $entity->getUntranslated()->language()->getId() && isset($translations[$language->getId()]); return AccessResult::allowedIf($has_translation)->cachePerRole()->cacheUntilEntityChanges($entity)->andIf($handler->getTranslationAccess($entity, $operation)); } } // No opinion. return AccessResult::neutral(); }
/** * {@inheritdoc} */ public function build() { /** @var $entity \Drupal\Core\Entity\EntityInterface */ $entity = $this->getContextValue('entity'); $view_builder = $this->entityManager->getViewBuilder($entity->getEntityTypeId()); return $view_builder->view($entity, $this->configuration['view_mode']); }
/** * {@inheritdoc} */ public function getForm(EntityInterface $entity, $operation = 'default', array $form_state_additions = array()) { $form_object = $this->entityManager->getFormObject($entity->getEntityTypeId(), $operation); $form_object->setEntity($entity); $form_state = (new FormState())->setFormState($form_state_additions); return $this->formBuilder->buildForm($form_object, $form_state); }
/** * Constructs a Date object. * * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager * The entity manager. * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager * The language manager. * @param \Drupal\Core\StringTranslation\TranslationInterface $translation * The string translation. * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory * The configuration factory. */ public function __construct(EntityManagerInterface $entity_manager, LanguageManagerInterface $language_manager, TranslationInterface $translation, ConfigFactoryInterface $config_factory) { $this->dateFormatStorage = $entity_manager->getStorage('date_format'); $this->languageManager = $language_manager; $this->stringTranslation = $translation; $this->configFactory = $config_factory; }
/** * Test row skipping when we can't get an entity to save. * * @covers ::import * @expectedException \Drupal\migrate\MigrateException * @expectedExceptionMessage Unable to get entity */ public function testImportEntityLoadFailure() { $bundles = []; $destination = new EntityTestDestination([], '', [], $this->migration->reveal(), $this->storage->reveal(), $bundles, $this->entityManager->reveal(), $this->prophesize(FieldTypePluginManagerInterface::class)->reveal()); $destination->setEntity(FALSE); $destination->import(new Row([], [])); }
/** * {@inheritdoc} */ public function getDescription() { $locked = $this->tempStore->getMetadata($this->entity->id()); $account = $this->entityManager->getStorage('user')->load($locked->owner); $username = array('#theme' => 'username', '#account' => $account); return $this->t('By breaking this lock, any unsaved changes made by @user will be lost.', array('@user' => drupal_render($username))); }
/** * Listener for the ConfigImporter import event. */ public function onConfigImporterImport() { $entity_types = array_filter($this->entityManager->getDefinitions(), function (EntityTypeInterface $entity_type) { return $entity_type->isTranslatable(); }); $this->updateDefinitions($entity_types); }
/** * {@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); }