/** * Tests that a resource without authentication cannot be enabled. */ public function testAuthentication() { $this->resourceConfigStorage->create(['id' => 'entity.entity_test', 'granularity' => RestResourceConfigInterface::METHOD_GRANULARITY, 'configuration' => ['GET' => ['supported_formats' => ['hal_json']]]])->save(); // Verify that accessing the resource returns 401. $response = $this->httpRequest($this->entity->urlInfo()->setRouteParameter('_format', $this->defaultFormat), 'GET'); // \Drupal\Core\Routing\RequestFormatRouteFilter considers the canonical, // non-REST route a match, but a lower quality one: no format restrictions // means there's always a match and hence when there is no matching REST // route, the non-REST route is used, but can't render into // application/hal+json, so it returns a 406. $this->assertResponse('406', 'HTTP response code is 406 when the resource does not define formats, because it falls back to the canonical, non-REST route.'); $this->curlClose(); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { // Remove the translated values. $this->entity = $this->entity->getUntranslated(); $this->entity->removeTranslation($this->language->getId()); $this->entity->save(); // Remove any existing path alias for the removed translation. // @todo This should be taken care of by the Path module. if (\Drupal::moduleHandler()->moduleExists('path')) { $path = $this->entity->urlInfo()->getInternalPath(); $conditions = array('source' => $path, 'langcode' => $this->language->getId()); \Drupal::service('path.alias_storage')->delete($conditions); } $form_state->setRedirectUrl($this->getCancelUrl()); }
/** * Tests the label formatter. */ public function testLabelFormatter() { $formatter = 'entity_reference_label'; // The 'link' settings is TRUE by default. $build = $this->buildRenderArray([$this->referencedEntity, $this->unsavedReferencedEntity], $formatter); $expected_item_1 = array('#type' => 'link', '#title' => $this->referencedEntity->label(), '#url' => $this->referencedEntity->urlInfo(), '#options' => $this->referencedEntity->urlInfo()->getOptions(), '#cache' => array('tags' => $this->referencedEntity->getCacheTags())); $this->assertEqual(drupal_render($build[0]), drupal_render($expected_item_1), sprintf('The markup returned by the %s formatter is correct for an item with a saved entity.', $formatter)); // The second referenced entity is "autocreated", therefore not saved and // lacking any URL info. $expected_item_2 = array('#markup' => $this->unsavedReferencedEntity->label(), '#cache' => array('tags' => $this->unsavedReferencedEntity->getCacheTags())); $this->assertEqual($build[1], $expected_item_2, sprintf('The markup returned by the %s formatter is correct for an item with a unsaved entity.', $formatter)); // Test with the 'link' setting set to FALSE. $build = $this->buildRenderArray([$this->referencedEntity, $this->unsavedReferencedEntity], $formatter, array('link' => FALSE)); $this->assertEqual($build[0]['#markup'], $this->referencedEntity->label(), sprintf('The markup returned by the %s formatter is correct for an item with a saved entity.', $formatter)); $this->assertEqual($build[1]['#markup'], $this->unsavedReferencedEntity->label(), sprintf('The markup returned by the %s formatter is correct for an item with a unsaved entity.', $formatter)); // Test an entity type that doesn't have any link templates, which means // \Drupal\Core\Entity\EntityInterface::urlInfo() will throw an exception // and the label formatter will output only the label instead of a link. $field_storage_config = FieldStorageConfig::loadByName($this->entityType, $this->fieldName); $field_storage_config->setSetting('target_type', 'entity_test_label'); $field_storage_config->save(); $referenced_entity_with_no_link_template = entity_create('entity_test_label', array('name' => $this->randomMachineName())); $referenced_entity_with_no_link_template->save(); $build = $this->buildRenderArray([$referenced_entity_with_no_link_template], $formatter, array('link' => TRUE)); $this->assertEqual($build[0]['#markup'], $referenced_entity_with_no_link_template->label(), sprintf('The markup returned by the %s formatter is correct for an entity type with no valid link template.', $formatter)); }
/** * Tests the label formatter. */ public function testLabelFormatter() { /** @var \Drupal\Core\Render\RendererInterface $renderer */ $renderer = $this->container->get('renderer'); $formatter = 'entity_reference_label'; // The 'link' settings is TRUE by default. $build = $this->buildRenderArray([$this->referencedEntity, $this->unsavedReferencedEntity], $formatter); $expected_field_cacheability = ['contexts' => [], 'tags' => [], 'max-age' => Cache::PERMANENT]; $this->assertEqual($build['#cache'], $expected_field_cacheability, 'The field render array contains the entity access cacheability metadata'); $expected_item_1 = array('#type' => 'link', '#title' => $this->referencedEntity->label(), '#url' => $this->referencedEntity->urlInfo(), '#options' => $this->referencedEntity->urlInfo()->getOptions(), '#cache' => array('contexts' => ['user.permissions'], 'tags' => $this->referencedEntity->getCacheTags())); $this->assertEqual($renderer->renderRoot($build[0]), $renderer->renderRoot($expected_item_1), sprintf('The markup returned by the %s formatter is correct for an item with a saved entity.', $formatter)); $this->assertEqual(CacheableMetadata::createFromRenderArray($build[0]), CacheableMetadata::createFromRenderArray($expected_item_1)); // The second referenced entity is "autocreated", therefore not saved and // lacking any URL info. $expected_item_2 = array('#plain_text' => $this->unsavedReferencedEntity->label(), '#cache' => array('contexts' => ['user.permissions'], 'tags' => $this->unsavedReferencedEntity->getCacheTags(), 'max-age' => Cache::PERMANENT)); $this->assertEqual($build[1], $expected_item_2, sprintf('The render array returned by the %s formatter is correct for an item with a unsaved entity.', $formatter)); // Test with the 'link' setting set to FALSE. $build = $this->buildRenderArray([$this->referencedEntity, $this->unsavedReferencedEntity], $formatter, array('link' => FALSE)); $this->assertEqual($build[0]['#plain_text'], $this->referencedEntity->label(), sprintf('The markup returned by the %s formatter is correct for an item with a saved entity.', $formatter)); $this->assertEqual($build[1]['#plain_text'], $this->unsavedReferencedEntity->label(), sprintf('The markup returned by the %s formatter is correct for an item with a unsaved entity.', $formatter)); // Test an entity type that doesn't have any link templates, which means // \Drupal\Core\Entity\EntityInterface::urlInfo() will throw an exception // and the label formatter will output only the label instead of a link. $field_storage_config = FieldStorageConfig::loadByName($this->entityType, $this->fieldName); $field_storage_config->setSetting('target_type', 'entity_test_label'); $field_storage_config->save(); $referenced_entity_with_no_link_template = EntityTestLabel::create(array('name' => $this->randomMachineName())); $referenced_entity_with_no_link_template->save(); $build = $this->buildRenderArray([$referenced_entity_with_no_link_template], $formatter, array('link' => TRUE)); $this->assertEqual($build[0]['#plain_text'], $referenced_entity_with_no_link_template->label(), sprintf('The markup returned by the %s formatter is correct for an entity type with no valid link template.', $formatter)); }
/** * {@inheritdoc} */ public function buildRow(EntityInterface $entity) { $row = array(); $row['date']['data'] = $entity->get('activity_date')->view(array('label' => 'hidden')); $row['title']['data'] = array('#type' => 'link', '#title' => SafeMarkup::checkPlain($entity->label()), '#url' => $entity->urlInfo()); $row['type'] = $entity->get('type')->entity->label(); return $row + parent::buildRow($entity); }
/** * {@inheritdoc} */ public function buildRow(EntityInterface $entity) { /* @var $entity \Drupal\commerce_store\Entity\Store */ $store_type = StoreType::load($entity->bundle()); $row['name']['data'] = ['#type' => 'link', '#title' => $entity->label()] + $entity->urlInfo()->toRenderArray(); $row['type'] = $store_type->label(); return $row + parent::buildRow($entity); }
/** * {@inheritdoc} */ public function buildRow(EntityInterface $entity) { $row = array(); $row['label']['data'] = array('#type' => 'link', '#title' => SafeMarkup::checkPlain($entity->label()), '#url' => $entity->urlInfo()); $row['type'] = SafeMarkup::checkPlain($entity->get('type')->entity->label()); $row['changed'] = $this->dateFormatter->format($entity->get('changed')->value, 'short'); return $row + parent::buildRow($entity); }
public function assertNoEntityAliasExists(EntityInterface $entity, $alias = NULL) { $path = array('source' => '/' . $entity->urlInfo()->getInternalPath()); if (!empty($alias)) { $path['alias'] = $alias; } $this->assertNoAliasExists($path); }
/** * Tests that a resource without authentication cannot be enabled. */ public function testAuthentication() { $settings = array('entity:entity_test' => array('GET' => array('supported_formats' => array('hal_json')))); // Attempt to enable the resource. $this->config->set('resources', $settings); $this->config->save(); $this->rebuildCache(); // Verify that accessing the resource returns 401. $response = $this->httpRequest($this->entity->urlInfo()->setRouteParameter('_format', $this->defaultFormat), 'GET'); // \Drupal\Core\Routing\RequestFormatRouteFilter considers the canonical, // non-REST route a match, but a lower quality one: no format restrictions // means there's always a match and hence when there is no matching REST // route, the non-REST route is used, but can't render into // application/hal+json, so it returns a 406. $this->assertResponse('406', 'HTTP response code is 406 when the resource does not define formats, because it falls back to the canonical, non-REST route.'); $this->curlClose(); }
/** * Prepares the link to the node. * * @param \Drupal\Core\Entity\EntityInterface $node * The node entity this field belongs to. * @param ResultRow $values * The values retrieved from the view's result set. * * @return string * Returns a string for the link text. */ protected function renderLink($node, ResultRow $values) { if ($node->access('view')) { $this->options['alter']['make_link'] = TRUE; $this->options['alter']['url'] = $node->urlInfo(); $text = !empty($this->options['text']) ? $this->options['text'] : $this->t('View'); return $text; } }
/** * {@inheritdoc} */ protected function renderLink(EntityInterface $entity, ResultRow $values) { if ($entity && $entity->access('update')) { $this->options['alter']['make_link'] = TRUE; $text = !empty($this->options['text']) ? $this->options['text'] : $this->t('Edit'); $this->options['alter']['url'] = $entity->urlInfo('edit-form', ['query' => ['destination' => $this->getDestinationArray()]]); return $text; } }
/** * {@inheritdoc} */ public function buildRow(EntityInterface $entity) { /** @var \Drupal\commerce_product\Entity\ProductTypeInterface $product_type */ $product_type = ProductType::load($entity->bundle()); $row['title']['data'] = ['#type' => 'link', '#title' => $entity->label()] + $entity->urlInfo()->toRenderArray(); $row['type'] = $product_type->label(); $row['status'] = $entity->isPublished() ? $this->t('Published') : $this->t('Unpublished'); return $row + parent::buildRow($entity); }
/** * Checks that workflows have the expected behaviors for the given user. * * @param \Drupal\user\UserInterface $user * The user to test the workflow behavior against. * @param array $expected_status * The an associative array with the operation name as key and the expected * status as value. */ protected function assertWorkflows(UserInterface $user, $expected_status) { $default_langcode = $this->langcodes[0]; $languages = $this->container->get('language_manager')->getLanguages(); $args = array('@user_label' => $user->getUsername()); $this->drupalLogin($user); // Check whether the user is allowed to access the entity form in edit mode. $options = array('language' => $languages[$default_langcode], 'absolute' => TRUE); $edit_url = $this->entity->urlInfo('edit-form', $options); $this->drupalGet($edit_url, $options); $this->assertResponse($expected_status['edit'], format_string('The @user_label has the expected edit access.', $args)); // Check whether the user is allowed to access the translation overview. $langcode = $this->langcodes[1]; $options = array('language' => $languages[$langcode], 'absolute' => TRUE); $translations_url = $this->entity->url('drupal:content-translation-overview', $options); $this->drupalGet($translations_url); $this->assertResponse($expected_status['overview'], format_string('The @user_label has the expected translation overview access.', $args)); // Check whether the user is allowed to create a translation. $add_translation_url = Url::fromRoute('content_translation.translation_add_' . $this->entityTypeId, [$this->entityTypeId => $this->entity->id(), 'source' => $default_langcode, 'target' => $langcode], $options); if ($expected_status['add_translation'] == 200) { $this->clickLink('Add'); $this->assertUrl($add_translation_url->toString(), array(), 'The translation overview points to the translation form when creating translations.'); // Check that the translation form does not contain shared elements for // translators. if ($expected_status['edit'] == 403) { $this->assertNoSharedElements(); } } else { $this->drupalGet($add_translation_url); } $this->assertResponse($expected_status['add_translation'], format_string('The @user_label has the expected translation creation access.', $args)); // Check whether the user is allowed to edit a translation. $langcode = $this->langcodes[2]; $options['language'] = $languages[$langcode]; $edit_translation_url = Url::fromRoute('content_translation.translation_edit_' . $this->entityTypeId, [$this->entityTypeId => $this->entity->id(), 'language' => $langcode], $options); $options = ['language' => $languages[$langcode], 'absolute' => TRUE]; if ($expected_status['edit_translation'] == 200) { $this->drupalGet($translations_url); $editor = $expected_status['edit'] == 200; if ($editor) { $this->clickLink('Edit', 2); // An editor should be pointed to the entity form in multilingual mode. // We need a new expected edit path with a new language. $expected_edit_path = $this->entity->url('edit-form', $options); $this->assertUrl($expected_edit_path, [], 'The translation overview points to the edit form for editors when editing translations.'); } else { $this->clickLink('Edit'); // While a translator should be pointed to the translation form. $this->assertUrl($edit_translation_url->toString(), array(), 'The translation overview points to the translation form for translators when editing translations.'); // Check that the translation form does not contain shared elements. $this->assertNoSharedElements(); } } else { $this->drupalGet($edit_translation_url); } $this->assertResponse($expected_status['edit_translation'], format_string('The @user_label has the expected translation creation access.', $args)); }
/** * Creates entity path alias. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity that should get an alias. * @param string $alias * The alias to be created. */ protected function doExecute(EntityInterface $entity, $alias) { // We need to save the entity before we can get its internal path. if ($entity->isNew()) { $entity->save(); } $path = $entity->urlInfo()->getInternalPath(); $langcode = $entity->language()->getId(); $this->aliasStorage->save($path, $alias, $langcode); }
/** * {@inheritdoc} */ protected function renderLink(EntityInterface $entity, ResultRow $values) { if ($entity && $entity->access('delete')) { $this->options['alter']['make_link'] = TRUE; $text = !empty($this->options['text']) ? $this->options['text'] : $this->t('Cancel account'); $this->options['alter']['url'] = $entity->urlInfo('cancel-form'); $this->options['alter']['query'] = drupal_get_destination(); return $text; } }
/** * Form constructor. * * @param array $form * An associative array containing the structure of the form. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the form. * @param \Drupal\Core\Entity\EntityInterface $node * The node being previews * * @return array * The form structure. */ public function buildForm(array $form, FormStateInterface $form_state, EntityInterface $node = NULL) { $view_mode = $node->preview_view_mode; $query_options = $node->isNew() ? array('query' => array('uuid' => $node->uuid())) : array(); $form['backlink'] = array('#type' => 'link', '#title' => $this->t('Back to content editing'), '#url' => $node->isNew() ? Url::fromRoute('node.add', ['node_type' => $node->bundle()]) : $node->urlInfo('edit-form'), '#options' => array('attributes' => array('class' => array('node-preview-backlink'))) + $query_options); $view_mode_options = $this->getViewModeOptions($node); $form['uuid'] = array('#type' => 'value', '#value' => $node->uuid()); $form['view_mode'] = array('#type' => 'select', '#title' => $this->t('View mode'), '#options' => $view_mode_options, '#default_value' => $view_mode, '#attributes' => array('data-drupal-autosubmit' => TRUE)); $form['submit'] = array('#type' => 'submit', '#value' => $this->t('Switch'), '#attributes' => array('class' => array('js-hide'))); return $form; }
/** * Prepares the link to the node. * * @param \Drupal\Core\Entity\EntityInterface $node * The node entity this field belongs to. * @param ResultRow $values * The values retrieved from the view's result set. * * @return string * Returns a string for the link text. */ protected function renderLink($node, ResultRow $values) { // Ensure user has access to edit this node. if (!$node->access('update')) { return; } $this->options['alter']['make_link'] = TRUE; $this->options['alter']['url'] = $node->urlInfo('edit-form'); $this->options['alter']['query'] = $this->getDestinationArray(); $text = !empty($this->options['text']) ? $this->options['text'] : $this->t('Edit'); return $text; }
/** * Prepares the link to delete a node. * * @param \Drupal\Core\Entity\EntityInterface $node * The node entity this field belongs to. * @param \Drupal\views\ResultRow $values * The values retrieved from the view's result set. * * @return string * Returns a string for the link text. */ protected function renderLink($node, ResultRow $values) { // Ensure user has access to delete this node. if (!$node->access('delete')) { return; } $this->options['alter']['make_link'] = TRUE; $this->options['alter']['url'] = $node->urlInfo('delete-form'); $this->options['alter']['query'] = drupal_get_destination(); $text = !empty($this->options['text']) ? $this->options['text'] : $this->t('Delete'); return $text; }
/** * {@inheritdoc} */ public function buildRow(EntityInterface $entity) { $uri = $entity->urlInfo(); $options = $uri->getOptions(); $uri->setOptions($options); $row['title']['data'] = ['#type' => 'link', '#title' => $entity->label(), '#url' => $uri]; $row['type'] = SafeMarkup::checkPlain($entity->getType()->label()); $row['author']['data'] = ['#theme' => 'username', '#account' => $entity->getOwner()]; $row['status'] = $entity->isActive() ? $this->t('active') : $this->t('not active'); $row['imported'] = $this->dateFormatter->format($entity->getImportedTime(), 'short'); $row['operations']['data'] = $this->buildOperations($entity); return $row + parent::buildRow($entity); }
/** * @inheritDoc */ public function buildRow(EntityInterface $entity) { $langcode = $entity->language()->getId(); $uri = $entity->urlInfo(); $options = $uri->getOptions(); $options += $langcode != LanguageInterface::LANGCODE_NOT_SPECIFIED && isset($languages[$langcode]) ? array('language' => $languages[$langcode]) : array(); $uri->setOptions($options); $row['fullname']['data'] = array('#type' => 'link', '#title' => $entity->label(), '#url' => $uri); $row['shortname']['data'] = array('#markup' => $entity->get('shortname')->value); $row['category']['data'] = array('#markup' => $entity->getCategoryInstance() ? $entity->getCategoryInstance()->get('name')->value : ''); $row['timemodified']['data'] = array('#markup' => $this->formatDate($entity, 'timemodified', 'short')); return $row; }
/** * Returns an array of supported actions for the current entity form. * * @todo Consider introducing a 'preview' action here, since it is used by * many entity types. */ protected function actions(array $form, FormStateInterface $form_state) { // @todo Rename the action key from submit to save. $actions['submit'] = array('#type' => 'submit', '#value' => $this->t('Save'), '#validate' => array(array($this, 'validate')), '#submit' => array(array($this, 'submit'), array($this, 'save'))); if (!$this->entity->isNew() && $this->entity->hasLinkTemplate('delete-form')) { $route_info = $this->entity->urlInfo('delete-form'); if ($this->getRequest()->query->has('destination')) { $query = $route_info->getOption('query'); $query['destination'] = $this->getRequest()->query->get('destination'); $route_info->setOption('query', $query); } $actions['delete'] = array('#type' => 'link', '#title' => $this->t('Delete'), '#access' => $this->entity->access('delete'), '#attributes' => array('class' => array('button', 'button--danger'))); $actions['delete'] += $route_info->toRenderArray(); } return $actions; }
/** * Returns an array of supported actions for the current entity form. * * @todo Consider introducing a 'preview' action here, since it is used by * many entity types. */ protected function actions(array $form, FormStateInterface $form_state) { // @todo Consider renaming the action key from submit to save. The impacts // are hard to predict. For example, see // \Drupal\language\Element\LanguageConfiguration::processLanguageConfiguration(). $actions['submit'] = array('#type' => 'submit', '#value' => $this->t('Save'), '#validate' => array('::validate'), '#submit' => array('::submitForm', '::save')); if (!$this->entity->isNew() && $this->entity->hasLinkTemplate('delete-form')) { $route_info = $this->entity->urlInfo('delete-form'); if ($this->getRequest()->query->has('destination')) { $query = $route_info->getOption('query'); $query['destination'] = $this->getRequest()->query->get('destination'); $route_info->setOption('query', $query); } $actions['delete'] = array('#type' => 'link', '#title' => $this->t('Delete'), '#access' => $this->entity->access('delete'), '#attributes' => array('class' => array('button', 'button--danger'))); $actions['delete']['#url'] = $route_info; } return $actions; }
/** * {@inheritdoc} */ public function buildRow(EntityInterface $entity) { /** @var \Drupal\node\NodeInterface $entity */ $mark = array('#theme' => 'mark', '#mark_type' => node_mark($entity->id(), $entity->getChangedTime())); $langcode = $entity->language()->getId(); $uri = $entity->urlInfo(); $options = $uri->getOptions(); $options += $langcode != LanguageInterface::LANGCODE_NOT_SPECIFIED && isset($languages[$langcode]) ? array('language' => $languages[$langcode]) : array(); $uri->setOptions($options); $row['title']['data'] = array('#type' => 'link', '#title' => $entity->label(), '#suffix' => ' ' . drupal_render($mark), '#url' => $uri); $row['type'] = node_get_type_label($entity); $row['author']['data'] = array('#theme' => 'username', '#account' => $entity->getOwner()); $row['status'] = $entity->isPublished() ? $this->t('published') : $this->t('not published'); $row['changed'] = $this->dateFormatter->format($entity->getChangedTime(), 'short'); $language_manager = \Drupal::languageManager(); if ($language_manager->isMultilingual()) { $row['language_name'] = $language_manager->getLanguageName($langcode); } $row['operations']['data'] = $this->buildOperations($entity); return $row + parent::buildRow($entity); }
/** * Form constructor for the comment reply form. * * There are several cases that have to be handled, including: * - replies to comments * - replies to entities * - attempts to reply to entities that can no longer accept comments * - respecting access permissions ('access comments', 'post comments', * etc.) * * @param \Symfony\Component\HttpFoundation\Request $request * The current request object. * @param \Drupal\Core\Entity\EntityInterface $entity * The entity this comment belongs to. * @param string $field_name * The field_name to which the comment belongs. * @param int $pid * (optional) Some comments are replies to other comments. In those cases, * $pid is the parent comment's comment ID. Defaults to NULL. * * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException * @return array|\Symfony\Component\HttpFoundation\RedirectResponse * One of the following: * An associative array containing: * - An array for rendering the entity or parent comment. * - comment_entity: If the comment is a reply to the entity. * - comment_parent: If the comment is a reply to another comment. * - comment_form: The comment form as a renderable array. * - A redirect response to current node: * - If user is not authorized to post comments. * - If parent comment doesn't belong to current entity. * - If user is not authorized to view comments. * - If current entity comments are disable. */ public function getReplyForm(Request $request, EntityInterface $entity, $field_name, $pid = NULL) { // Check if entity and field exists. $fields = $this->commentManager->getFields($entity->getEntityTypeId()); if (empty($fields[$field_name])) { throw new NotFoundHttpException(); } $account = $this->currentUser(); $uri = $entity->urlInfo()->setAbsolute(); $build = array(); // Check if the user has the proper permissions. if (!$account->hasPermission('post comments')) { drupal_set_message($this->t('You are not authorized to post comments.'), 'error'); return new RedirectResponse($uri->toString()); } // The user is not just previewing a comment. if ($request->request->get('op') != $this->t('Preview')) { $status = $entity->{$field_name}->status; if ($status != CommentItemInterface::OPEN) { drupal_set_message($this->t("This discussion is closed: you can't post new comments."), 'error'); return new RedirectResponse($uri->toString()); } // $pid indicates that this is a reply to a comment. if ($pid) { // Check if the user has the proper permissions. if (!$account->hasPermission('access comments')) { drupal_set_message($this->t('You are not authorized to view comments.'), 'error'); return new RedirectResponse($uri->toString()); } // Load the parent comment. $comment = $this->entityManager()->getStorage('comment')->load($pid); // Check if the parent comment is published and belongs to the entity. if (!$comment->isPublished() || $comment->getCommentedEntityId() != $entity->id()) { drupal_set_message($this->t('The comment you are replying to does not exist.'), 'error'); return new RedirectResponse($uri->toString()); } // Display the parent comment. $build['comment_parent'] = $this->entityManager()->getViewBuilder('comment')->view($comment); } elseif ($entity->access('view', $account)) { // We make sure the field value isn't set so we don't end up with a // redirect loop. $entity = clone $entity; $entity->{$field_name}->status = CommentItemInterface::HIDDEN; // Render array of the entity full view mode. $build['commented_entity'] = $this->entityManager()->getViewBuilder($entity->getEntityTypeId())->view($entity, 'full'); unset($build['commented_entity']['#cache']); } } else { $build['#title'] = $this->t('Preview comment'); } // Show the actual reply box. $comment = $this->entityManager()->getStorage('comment')->create(array('entity_id' => $entity->id(), 'pid' => $pid, 'entity_type' => $entity->getEntityTypeId(), 'field_name' => $field_name)); $build['comment_form'] = $this->entityFormBuilder()->getForm($comment); return $build; }
/** * {@inheritdoc} */ public function updateAlias(EntityInterface $entity, $op, array $options = array()) { // Skip if the entity does not have the path field. if (!$entity instanceof ContentEntityInterface || !$entity->hasField('path')) { return NULL; } // Skip if pathauto processing is disabled. if (isset($entity->path->pathauto) && empty($entity->path->pathauto) && empty($options['force'])) { return NULL; } $options += array('language' => $entity->language()->getId()); $type = $entity->getEntityTypeId(); $bundle = $entity->bundle(); // Skip processing if the entity has no pattern. if (!$this->getPatternByEntity($type, $bundle, $options['language'])) { return NULL; } // Deal with taxonomy specific logic. if ($type == 'taxonomy_term') { $config_forum = $this->configFactory->get('forum.settings'); if ($entity->getVocabularyId() == $config_forum->get('vocabulary')) { $type = 'forum'; } } $result = $this->createAlias($type, $op, '/' . $entity->urlInfo()->getInternalPath(), array($type => $entity), $bundle, $options['language']); if ($type == 'taxonomy_term' && empty($options['is_child'])) { // For all children generate new aliases. $options['is_child'] = TRUE; unset($options['language']); foreach ($this->getTermTree($entity->getVocabularyId(), $entity->id(), NULL, TRUE) as $subterm) { $this->updateAlias($subterm, $op, $options); } } return $result; }
/** * Constructs the entity URI. * * @param \Drupal\Core\Entity\EntityInterface * The entity. * @return string * The entity URI. */ protected function getEntityUri(EntityInterface $entity) { // Some entity types don't provide a canonical link template, at least call // out to ->url(). if ($entity->isNew() || !$entity->hasLinkTemplate('canonical')) { return $entity->url('canonical', []); } $url = $entity->urlInfo('canonical', ['absolute' => TRUE]); return $url->setRouteParameter('_format', 'hal_json')->toString(); }
/** * Creates a \Drupal\Core\Url object based on the entity and link template. * * Method urlInfo() is deprecated and replaced with toUrl(). * See also getTestToUrl(). * * @param \Drupal\Core\Entity\EntityInterface $entity * The test entity. * @param string $link_template * The link template. * @param string $langcode * The langcode. * * @return \Drupal\Core\Url * The URL for this entity's link template. */ protected function getTestUrlInfo(EntityInterface $entity, $link_template, array $options = [], $langcode = NULL) { $entity_type = $this->getMock('Drupal\\Core\\Entity\\EntityTypeInterface'); $entity_type->expects($this->any())->method('getLinkTemplates')->will($this->returnValue(array('edit-form' => 'test_entity_type.edit'))); if ($langcode) { $entity->langcode = $langcode; } $this->entityManager->expects($this->any())->method('getDefinition')->with('test_entity_type')->will($this->returnValue($entity_type)); // If no link template is given, call without a value to test the default. if ($link_template) { $uri = $entity->urlInfo($link_template, $options); } else { if ($entity instanceof ConfigEntityInterface) { $uri = $entity->urlInfo('edit-form', $options); } else { $uri = $entity->urlInfo('canonical', $options); } } return $uri; }
function saveEntityAlias($entity_type, EntityInterface $entity, $alias, $language = Language::LANGCODE_NOT_SPECIFIED) { $uri = $entity->urlInfo()->toArray(); return $this->saveAlias($uri['path'], $alias, $language); }
/** * {@inheritdoc} */ public function getCancelUrl() { return $this->entity->urlInfo('drupal:content-translation-overview'); }
/** * Form constructor for the comment reply form. * * There are several cases that have to be handled, including: * - replies to comments * - replies to entities * * @param \Symfony\Component\HttpFoundation\Request $request * The current request object. * @param \Drupal\Core\Entity\EntityInterface $entity * The entity this comment belongs to. * @param string $field_name * The field_name to which the comment belongs. * @param int $pid * (optional) Some comments are replies to other comments. In those cases, * $pid is the parent comment's comment ID. Defaults to NULL. * * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException * @return array|\Symfony\Component\HttpFoundation\RedirectResponse * An associative array containing: * - An array for rendering the entity or parent comment. * - comment_entity: If the comment is a reply to the entity. * - comment_parent: If the comment is a reply to another comment. * - comment_form: The comment form as a renderable array. */ public function getReplyForm(Request $request, EntityInterface $entity, $field_name, $pid = NULL) { $account = $this->currentUser(); $uri = $entity->urlInfo()->setAbsolute(); $build = array(); // The user is not just previewing a comment. if ($request->request->get('op') != $this->t('Preview')) { // $pid indicates that this is a reply to a comment. if ($pid) { // Load the parent comment. $comment = $this->entityManager()->getStorage('comment')->load($pid); // Display the parent comment. $build['comment_parent'] = $this->entityManager()->getViewBuilder('comment')->view($comment); } elseif ($entity->access('view', $account)) { // We make sure the field value isn't set so we don't end up with a // redirect loop. $entity = clone $entity; $entity->{$field_name}->status = CommentItemInterface::HIDDEN; // Render array of the entity full view mode. $build['commented_entity'] = $this->entityManager()->getViewBuilder($entity->getEntityTypeId())->view($entity, 'full'); unset($build['commented_entity']['#cache']); } } else { $build['#title'] = $this->t('Preview comment'); } // Show the actual reply box. $comment = $this->entityManager()->getStorage('comment')->create(array('entity_id' => $entity->id(), 'pid' => $pid, 'entity_type' => $entity->getEntityTypeId(), 'field_name' => $field_name)); $build['comment_form'] = $this->entityFormBuilder()->getForm($comment); return $build; }