Commit f7ecd6ba authored by catch's avatar catch
Browse files

Issue #3090187 by ilya.no, andypost, AdamPS, abx: Mechanism to disable...

Issue #3090187 by ilya.no, andypost, AdamPS, abx: Mechanism to disable preprocessing of base fields in comment entity type so they can be configured via the field UI

(cherry picked from commit 5fb8e243)
parent b45e6954
Loading
Loading
Loading
Loading
+62 −35
Original line number Diff line number Diff line
@@ -546,6 +546,15 @@ function comment_preprocess_block(&$variables) {
/**
 * Prepares variables for comment templates.
 *
 * By default this function performs special preprocessing of some base fields
 * so they are available as variables in the template. For example 'subject'
 * appears as 'title'. This preprocessing is skipped if:
 * - a module makes the field's display configurable via the field UI by means
 *   of BaseFieldDefinition::setDisplayConfigurable()
 * - AND the additional entity type property
 *   'enable_base_field_custom_preprocess_skipping' has been set using
 *   hook_entity_type_build().
 *
 * Default template: comment.html.twig.
 *
 * @param array $variables
@@ -563,6 +572,17 @@ function template_preprocess_comment(&$variables) {
  $variables['commented_entity'] = $commented_entity;
  $variables['threaded'] = $variables['elements']['#comment_threaded'];

  $skip_custom_preprocessing = $comment->getEntityType()->get('enable_base_field_custom_preprocess_skipping');

  // Make created, uid, pid and subject fields available separately. Skip this
  // custom preprocessing if the field display is configurable and skipping has
  // been enabled.
  // @todo https://www.drupal.org/project/drupal/issues/3015623
  //   Eventually delete this code and matching template lines. Using
  //   $variables['content'] is more flexible and consistent.
  $submitted_configurable = $comment->getFieldDefinition('created')->isDisplayConfigurable('view') || $comment->getFieldDefinition('uid')->isDisplayConfigurable('view');

  if (!$skip_custom_preprocessing || !$submitted_configurable) {
    $account = $comment->getOwner();
    $username = [
      '#theme' => 'username',
@@ -591,23 +611,17 @@ function template_preprocess_comment(&$variables) {
      $variables['user_picture'] = [];
    }

    $variables['submitted'] = t('Submitted by @username on @datetime', ['@username' => $variables['author'], '@datetime' => $variables['created']]);
  }

  if (isset($comment->in_preview)) {
    $variables['title'] = Link::fromTextAndUrl($comment->getSubject(), Url::fromRoute('<front>'))->toString();
    $variables['permalink'] = Link::fromTextAndUrl(t('Permalink'), Url::fromRoute('<front>'))->toString();
  }
  else {
    $uri = $comment->permalink();
    $attributes = $uri->getOption('attributes') ?: [];
    $attributes += ['class' => ['permalink'], 'rel' => 'bookmark'];
    $uri->setOption('attributes', $attributes);
    $variables['title'] = Link::fromTextAndUrl($comment->getSubject(), $uri)->toString();

    $variables['permalink'] = Link::fromTextAndUrl(t('Permalink'), $comment->permalink())->toString();
  }

  $variables['submitted'] = t('Submitted by @username on @datetime', ['@username' => $variables['author'], '@datetime' => $variables['created']]);

  if ($comment_parent = $comment->getParentComment()) {
  if (($comment_parent = $comment->getParentComment()) && (!$skip_custom_preprocessing || !$comment->getFieldDefinition('pid')->isDisplayConfigurable('view'))) {
    // Fetch and store the parent comment information for use in templates.
    $account_parent = $comment_parent->getOwner();
    $variables['parent_comment'] = $comment_parent;
@@ -643,6 +657,19 @@ function template_preprocess_comment(&$variables) {
    $variables['parent'] = '';
  }

  if (!$skip_custom_preprocessing || !$comment->getFieldDefinition('subject')->isDisplayConfigurable('view')) {
    if (isset($comment->in_preview)) {
      $variables['title'] = Link::fromTextAndUrl($comment->getSubject(), Url::fromRoute('<front>'))->toString();
    }
    else {
      $uri = $comment->permalink();
      $attributes = $uri->getOption('attributes') ?: [];
      $attributes += ['class' => ['permalink'], 'rel' => 'bookmark'];
      $uri->setOption('attributes', $attributes);
      $variables['title'] = Link::fromTextAndUrl($comment->getSubject(), $uri)->toString();
    }
  }

  // Helpful $content variable for templates.
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
+29 −25
Original line number Diff line number Diff line
@@ -4,7 +4,7 @@
 * Default theme implementation for comments.
 *
 * Available variables:
 * - author: Comment author. Can be a link or plain text.
 * - author: (optional) Comment author. Can be a link or plain text.
 * - content: The content-related items for the comment display. Use
 *   {{ content }} to print them all, or print a subset such as
 *   {{ content.field_example }}. Use the following code to temporarily suppress
@@ -12,19 +12,21 @@
 *   @code
 *   {{ content|without('field_example') }}
 *   @endcode
 * - created: Formatted date and time for when the comment was created.
 *   Preprocess functions can reformat it by calling DateFormatter::format()
 *   with the desired parameters on the 'comment.created' variable.
 * - changed: Formatted date and time for when the comment was last changed.
 *   Preprocess functions can reformat it by calling DateFormatter::format()
 *   with the desired parameters on the 'comment.changed' variable.
 * - created: (optional) Formatted date and time for when the comment was
 *   created. Preprocess functions can reformat it by calling
 *   DateFormatter::format() with the desired parameters on the
 *   'comment.created' variable.
 * - changed: (optional) Formatted date and time for when the comment was last
 *   changed. Preprocess functions can reformat it by calling
 *   DateFormatter::format() with the desired parameters on the
 *   'comment.changed' variable.
 * - permalink: Comment permalink.
 * - submitted: Submission information created from author and created
 *   during template_preprocess_comment().
 * - user_picture: The comment author's profile picture.
 * - submitted: (optional) Submission information created from author and
 *   created during template_preprocess_comment().
 * - user_picture: (optional) The comment author's profile picture.
 * - status: Comment status. Possible values are:
 *   unpublished, published, or preview.
 * - title: Comment title, linked to the comment.
 * - title: (optional) Comment title, linked to the comment.
 * - attributes: HTML attributes for the containing element.
 *   The attributes.class may contain one or more of the following classes:
 *   - comment: The current template type; for instance, 'theming hook'.
@@ -44,7 +46,7 @@
 * - threaded: A flag indicating whether the comments are threaded or not.
 *
 * These variables are provided to give context about the parent comment (if
 * any):
 * any, optional):
 * - parent_comment: Full parent comment entity (if any).
 * - parent_author: Equivalent to author for the parent comment.
 * - parent_created: Equivalent to created for the parent comment.
@@ -75,6 +77,7 @@
  #}
  <mark class="hidden" data-comment-timestamp="{{ new_indicator_timestamp }}"></mark>

  {% if submitted %}
    <footer>
      {{ user_picture }}
      <p>{{ submitted }}</p>
@@ -90,6 +93,7 @@

      {{ permalink }}
    </footer>
  {% endif %}

  <div{{ content_attributes }}>
    {% if title %}
+5 −0
Original line number Diff line number Diff line
name: 'Comment configurable display module tests'
type: module
description: 'Support module for comment \Drupal\Core\Field\BaseFieldDefinition::setDisplayConfigurable() testing.'
package: Testing
version: VERSION
+28 −0
Original line number Diff line number Diff line
<?php

/**
 * @file
 * A module for testing making comment base fields' displays configurable.
 */

use Drupal\Core\Entity\EntityTypeInterface;

/**
 * Implements hook_entity_base_field_info_alter().
 */
function comment_display_configurable_test_entity_base_field_info_alter(&$base_field_definitions, EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'comment') {
    foreach (['created', 'uid', 'pid', 'subject'] as $field) {
      /** @var \Drupal\Core\Field\BaseFieldDefinition[] $base_field_definitions */
      $base_field_definitions[$field]->setDisplayConfigurable('view', TRUE);
    }
  }
}

/**
 * Implements hook_entity_type_build().
 */
function comment_display_configurable_test_entity_type_build(array &$entity_types) {
  // Allow skipping of extra preprocessing for configurable display.
  $entity_types['comment']->set('enable_base_field_custom_preprocess_skipping', TRUE);
}
+82 −0
Original line number Diff line number Diff line
<?php

namespace Drupal\Tests\comment\Functional;

use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\Core\Language\LanguageInterface;
use Drupal\comment\CommentInterface;
use Drupal\comment\Entity\Comment;
use Drupal\user\RoleInterface;

/**
 * Tests making comment base fields' displays configurable.
 *
 * @group comment
 */
class CommentDisplayConfigurableTest extends CommentTestBase {

  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'bartik';

  protected function setUp(): void {
    parent::setUp();

    // Allow anonymous users to see comments.
    user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, [
      'access comments',
      'access content',
    ]);
  }

  /**
   * Sets base fields to configurable display and check settings are respected.
   */
  public function testDisplayConfigurable() {
    // Add a comment.
    $nid = $this->node->id();
    /** @var \Drupal\comment\CommentInterface $comment */
    $comment = Comment::create([
      'entity_id' => $nid,
      'entity_type' => 'node',
      'field_name' => 'comment',
      'uid' => $this->webUser->id(),
      'status' => CommentInterface::PUBLISHED,
      'subject' => $this->randomMachineName(),
      'language' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
      'comment_body' => [LanguageInterface::LANGCODE_NOT_SPECIFIED => [$this->randomMachineName()]],
    ]);
    $comment->save();
    $assert = $this->assertSession();

    // Check the comment author with Drupal default non-configurable display.
    $this->drupalGet('node/' . $nid);
    $assert->elementExists('css', 'p.comment__author span');

    // Enable module to make base fields' displays configurable.
    \Drupal::service('module_installer')->install(['comment_display_configurable_test']);

    // Configure display.
    $display = EntityViewDisplay::load('comment.comment.default');
    $display->setComponent('uid',
      [
        'type' => 'entity_reference_label',
        'label' => 'above',
        'settings' => ['link' => FALSE],
      ])
      ->save();
    // Recheck the comment author with configurable display.
    $this->drupalGet('node/' . $nid);
    $assert->elementExists('css', '.field--name-uid .field__item');

    // Remove from display.
    $display->removeComponent('uid')
      ->removeComponent('created')
      ->save();

    $this->drupalGet('node/' . $this->node->id());
    $assert->elementNotExists('css', '.field--name-uid .field__item');
  }

}
Loading