Exemple #1
1
 /**
  * {@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 convert($value, $definition, $name, array $defaults, Request $request)
 {
     $entity_type = substr($definition['type'], strlen('entity:'));
     if ($storage = $this->entityManager->getStorage($entity_type)) {
         return $storage->load($value);
     }
 }
 /**
  * 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);
 }
 /**
  * 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());
 }
 /**
  * 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;
 }
 /**
  * {@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());
 }
 /**
  * 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;
 }
 /**
  * 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;
 }
 /**
  * {@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}
  */
 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;
 }
Exemple #11
0
 /**
  * {@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)));
 }
Exemple #12
0
 /**
  * {@inheritdoc}
  */
 public function settingsForm(array $form, FormStateInterface $form_state)
 {
     $options = [];
     foreach ($this->entityManager->getStorage('image_style')->loadMultiple() as $id => $image_style) {
         $options[$id] = $image_style->label();
     }
     return ['image_style' => ['#type' => 'select', '#title' => t('Image style'), '#description' => t('Select image style to be used to display thumbnails.'), '#default_value' => $this->configuration['image_style'], '#options' => $options]];
 }
 /**
  * {@inheritdoc}
  */
 public function build(RouteMatchInterface $route_match)
 {
     $breadcrumb = array();
     $breadcrumb[] = $this->l($this->t('Home'), '<front>');
     $entity = $this->entityManager->getStorage($route_match->getParameter('entity_type'))->load($route_match->getParameter('entity_id'));
     $breadcrumb[] = \Drupal::linkGenerator()->generateFromUrl($entity->label(), $entity->urlInfo());
     return $breadcrumb;
 }
 /**
  * Get taxonomy permissions.
  *
  * @return array
  *   Permissions array.
  */
 public function permissions()
 {
     $permissions = [];
     foreach ($this->entityManager->getStorage('taxonomy_vocabulary')->loadMultiple() as $vocabulary) {
         $permissions += ['edit terms in ' . $vocabulary->id() => ['title' => $this->t('Edit terms in %vocabulary', ['%vocabulary' => $vocabulary->label()])]];
         $permissions += ['delete terms in ' . $vocabulary->id() => ['title' => $this->t('Delete terms from %vocabulary', ['%vocabulary' => $vocabulary->label()])]];
     }
     return $permissions;
 }
 /**
  * Returns an array of route objects.
  *
  * @return \Symfony\Component\Routing\Route[]
  *   An array of route objects.
  */
 public function routes()
 {
     $routes = array();
     /** @var $searchApiPage SearchApiPageInterface */
     foreach ($this->entityManager->getStorage('search_api_page')->loadMultiple() as $searchApiPage) {
         $routes['search_api_page.' . $searchApiPage->id()] = new Route('/' . $searchApiPage->getPath() . '/{keyword}', array('_controller' => 'Drupal\\search_api_page\\Controller\\SearchApiPageController::page', 'search_api_page' => $searchApiPage->id(), 'keyword' => ''), array('_access' => 'TRUE'));
     }
     return $routes;
 }
Exemple #16
0
 /**
  * {@inheritdoc}
  */
 public function calculateDependencies()
 {
     $dependencies = parent::calculateDependencies();
     $view_mode = $this->entityManager->getStorage('entity_view_mode')->load($this->entityTypeId . '.' . $this->options['view_mode']);
     if ($view_mode) {
         $dependencies[$view_mode->getConfigDependencyKey()][] = $view_mode->getConfigDependencyName();
     }
     return $dependencies;
 }
 function __construct(EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler)
 {
     $this->entityManger = $entity_manager;
     $this->moduleHandler = $module_handler;
     if ($this->entityManger && $this->moduleHandler->moduleExists('taxonomy')) {
         $this->termStorage = $this->entityManger->getStorage('taxonomy_term');
         $this->vocabularyStorage = $this->entityManger->getStorage('taxonomy_vocabulary');
     }
 }
Exemple #18
0
 /**
  * {@inheritdoc}
  */
 public function titleQuery()
 {
     $titles = array();
     $items = $this->entityManager->getStorage('aggregator_item')->loadMultiple($this->value);
     foreach ($items as $feed) {
         $titles[] = $feed->label();
     }
     return $titles;
 }
Exemple #19
0
 /**
  * {@inheritdoc}
  */
 public function titleQuery()
 {
     $titles = array();
     $feeds = $this->entityManager->getStorage('aggregator_feed')->loadMultiple($this->value);
     foreach ($feeds as $feed) {
         $titles[] = SafeMarkup::checkPlain($feed->label());
     }
     return $titles;
 }
 /**
  * Updates the current user's last access time.
  *
  * @param \Symfony\Component\HttpKernel\Event\PostResponseEvent $event
  *   The event to process.
  */
 public function onKernelTerminate(PostResponseEvent $event)
 {
     if ($this->account->isAuthenticated() && REQUEST_TIME - $this->account->getLastAccessedTime() > Settings::get('session_write_interval', 180)) {
         // Do that no more than once per 180 seconds.
         /** @var \Drupal\user\UserStorageInterface $storage */
         $storage = $this->entityManager->getStorage('user');
         $storage->updateLastAccessTimestamp($this->account, REQUEST_TIME);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function build(RouteMatchInterface $route_match)
 {
     $breadcrumb = new Breadcrumb();
     $breadcrumb->addCacheContexts(['route']);
     $links[] = Link::createFromRoute($this->t('Home'), '<front>');
     $vocabulary = $this->entityManager->getStorage('taxonomy_vocabulary')->load($this->config->get('vocabulary'));
     $breadcrumb->addCacheableDependency($vocabulary);
     $links[] = Link::createFromRoute($vocabulary->label(), 'forum.index');
     return $breadcrumb->setLinks($links);
 }
Exemple #22
0
 /**
  * Override the behavior of titleQuery(). Get the filenames.
  */
 public function titleQuery()
 {
     $fids = $this->entityQuery->get('file')->condition('fid', $this->value, 'IN')->execute();
     $controller = $this->entityManager->getStorage('file');
     $files = $controller->loadMultiple($fids);
     $titles = array();
     foreach ($files as $file) {
         $titles[] = $file->getFilename();
     }
     return $titles;
 }
 /**
  * {@inheritdoc}
  */
 public function execute()
 {
     $entity_type_id = $this->getContextValue('entity_type_id');
     $entity_id = $this->getContextValue('entity_id');
     $storage = $this->entityManager->getStorage($entity_type_id);
     $entity = $storage->load($entity_id);
     // @todo Refine the provided context definition for 'entity'. Example: if
     //  the loaded entity is a node then the provided context definition should
     //  use the type node. We don't have an API for that yet.
     $this->setProvidedValue('entity', $entity);
 }
 /**
  * {@inheritdoc}
  */
 public function validate($module)
 {
     $entity_types = $this->entityManager->getDefinitions();
     $reasons = array();
     foreach ($entity_types as $entity_type) {
         if ($module == $entity_type->getProvider() && $entity_type instanceof ContentEntityTypeInterface && $this->entityManager->getStorage($entity_type->id())->hasData()) {
             $reasons[] = $this->t('There is content for the entity type: @entity_type', array('@entity_type' => $entity_type->getLabel()));
         }
     }
     return $reasons;
 }
 /**
  * {@inheritdoc}
  */
 public function validate($module)
 {
     $entity_types = $this->entityManager->getDefinitions();
     $reasons = [];
     foreach ($entity_types as $entity_type) {
         if ($module == $entity_type->getProvider() && $entity_type instanceof ContentEntityTypeInterface && $this->entityManager->getStorage($entity_type->id())->hasData()) {
             $reasons[] = $this->t('There is content for the entity type: @entity_type. <a href=":url">Remove @entity_type_plural</a>.', ['@entity_type' => $entity_type->getLabel(), '@entity_type_plural' => $entity_type->getPluralLabel(), ':url' => Url::fromRoute('system.prepare_modules_entity_uninstall', ['entity_type_id' => $entity_type->id()])->toString()]);
         }
     }
     return $reasons;
 }
 /**
  * {@inheritdoc}
  */
 public function getDerivativeDefinitions($base_plugin_definition)
 {
     // Get all custom menu links which should be rediscovered.
     $entity_ids = $this->queryFactory->get('menu_link_content')->condition('rediscover', TRUE)->execute();
     $plugin_definitions = [];
     $menu_link_content_entities = $this->entityManager->getStorage('menu_link_content')->loadMultiple($entity_ids);
     /** @var \Drupal\menu_link_content\MenuLinkContentInterface $menu_link_content */
     foreach ($menu_link_content_entities as $menu_link_content) {
         $plugin_definitions[$menu_link_content->uuid()] = $menu_link_content->getPluginDefinition();
     }
     return $plugin_definitions;
 }
Exemple #27
0
 /**
  * {@inheritdoc}
  */
 public function access(AccountInterface $account)
 {
     // @todo Perhaps read config directly rather than load all feed types.
     $access_control_handler = $this->entityManager->getAccessControlHandler('feeds_feed');
     foreach ($this->entityManager->getStorage('feeds_feed_type')->loadByProperties(['status' => TRUE]) as $feed_type) {
         $access = $access_control_handler->createAccess($feed_type->id(), $account, [], TRUE);
         if ($access->isAllowed()) {
             return $access;
         }
     }
     return AccessResult::neutral();
 }
 /**
  * {@inheritdoc}
  */
 public function synchronizeFields(ContentEntityInterface $entity, $sync_langcode, $original_langcode = NULL)
 {
     $translations = $entity->getTranslationLanguages();
     $field_type_manager = \Drupal::service('plugin.manager.field.field_type');
     // If we have no information about what to sync to, if we are creating a new
     // entity, if we have no translations for the current entity and we are not
     // creating one, then there is nothing to synchronize.
     if (empty($sync_langcode) || $entity->isNew() || count($translations) < 2) {
         return;
     }
     // If the entity language is being changed there is nothing to synchronize.
     $entity_type = $entity->getEntityTypeId();
     $entity_unchanged = isset($entity->original) ? $entity->original : $this->entityManager->getStorage($entity_type)->loadUnchanged($entity->id());
     if ($entity->getUntranslated()->language()->getId() != $entity_unchanged->getUntranslated()->language()->getId()) {
         return;
     }
     /** @var \Drupal\Core\Field\FieldItemListInterface $items */
     foreach ($entity as $field_name => $items) {
         $field_definition = $items->getFieldDefinition();
         $field_type_definition = $field_type_manager->getDefinition($field_definition->getType());
         $column_groups = $field_type_definition['column_groups'];
         // Sync if the field is translatable, not empty, and the synchronization
         // setting is enabled.
         if ($field_definition instanceof ThirdPartySettingsInterface && $field_definition->isTranslatable() && !$items->isEmpty() && ($translation_sync = $field_definition->getThirdPartySetting('content_translation', 'translation_sync'))) {
             // Retrieve all the untranslatable column groups and merge them into
             // single list.
             $groups = array_keys(array_diff($translation_sync, array_filter($translation_sync)));
             if (!empty($groups)) {
                 $columns = array();
                 foreach ($groups as $group) {
                     $info = $column_groups[$group];
                     // A missing 'columns' key indicates we have a single-column group.
                     $columns = array_merge($columns, isset($info['columns']) ? $info['columns'] : array($group));
                 }
                 if (!empty($columns)) {
                     $values = array();
                     foreach ($translations as $langcode => $language) {
                         $values[$langcode] = $entity->getTranslation($langcode)->get($field_name)->getValue();
                     }
                     // If a translation is being created, the original values should be
                     // used as the unchanged items. In fact there are no unchanged items
                     // to check against.
                     $langcode = $original_langcode ?: $sync_langcode;
                     $unchanged_items = $entity_unchanged->getTranslation($langcode)->get($field_name)->getValue();
                     $this->synchronizeItems($values, $unchanged_items, $sync_langcode, array_keys($translations), $columns);
                     foreach ($translations as $langcode => $language) {
                         $entity->getTranslation($langcode)->get($field_name)->setValue($values[$langcode]);
                     }
                 }
             }
         }
     }
 }
 /**
  * Tests Rules default components.
  */
 public function testDefaultComponents()
 {
     $config_entity = $this->storage->load('rules_test_default_component');
     /** @var $config_entity RulesComponent */
     $expression = $config_entity->getExpression();
     $user = $this->entityManager->getStorage('user')->create(array('mail' => '*****@*****.**'));
     $expression->setContextValue('user', $user)->execute();
     // Test that the action was executed correctly.
     $messages = drupal_get_messages();
     $message_string = isset($messages['status'][0]) ? (string) $messages['status'][0] : NULL;
     $this->assertEqual($message_string, '*****@*****.**');
 }
 /**
  * {@inheritdoc}
  */
 public function collect(Request $request, Response $response, \Exception $exception = NULL)
 {
     $storage = $this->entityManager->getStorage('block');
     $loaded = $this->entityManager->getLoaded('block');
     $rendered = $this->entityManager->getRendered('block');
     if ($loaded) {
         $this->data['blocks']['loaded'] = $this->getBlocksData($loaded, $storage);
     }
     if ($rendered) {
         $this->data['blocks']['rendered'] = $this->getBlocksData($rendered, $storage);
     }
 }