function CommentInterfaceTest::testViewMode

Same name in other branches
  1. 8.9.x core/modules/comment/tests/src/Functional/CommentInterfaceTest.php \Drupal\Tests\comment\Functional\CommentInterfaceTest::testViewMode()
  2. 10 core/modules/comment/tests/src/Functional/CommentInterfaceTest.php \Drupal\Tests\comment\Functional\CommentInterfaceTest::testViewMode()
  3. 11.x core/modules/comment/tests/src/Functional/CommentInterfaceTest.php \Drupal\Tests\comment\Functional\CommentInterfaceTest::testViewMode()

Tests the comment formatter configured with a custom comment view mode.

File

core/modules/comment/tests/src/Functional/CommentInterfaceTest.php, line 306

Class

CommentInterfaceTest
Tests comment user interfaces.

Namespace

Drupal\Tests\comment\Functional

Code

public function testViewMode() {
    $this->drupalLogin($this->webUser);
    $this->drupalGet($this->node
        ->toUrl());
    $comment_text = $this->randomMachineName();
    // Post a comment.
    $this->postComment($this->node, $comment_text);
    // Comment displayed in 'default' display mode found and has body text.
    $comment_element = $this->cssSelect('#comment-1');
    $this->assertNotEmpty($comment_element);
    $this->assertSession()
        ->responseContains('<p>' . $comment_text . '</p>');
    // Create a new comment entity view mode.
    $mode = mb_strtolower($this->randomMachineName());
    EntityViewMode::create([
        'targetEntityType' => 'comment',
        'id' => "comment.{$mode}",
    ])->save();
    // Create the corresponding entity view display for article node-type. Note
    // that this new view display mode doesn't contain the comment body.
    EntityViewDisplay::create([
        'targetEntityType' => 'comment',
        'bundle' => 'comment',
        'mode' => $mode,
    ])->setStatus(TRUE)
        ->save();
    
    /** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $node_display */
    $node_display = EntityViewDisplay::load('node.article.default');
    $formatter = $node_display->getComponent('comment');
    // Change the node comment field formatter to use $mode mode instead of
    // 'default' mode.
    $formatter['settings']['view_mode'] = $mode;
    $node_display->setComponent('comment', $formatter)
        ->save();
    // Reloading the node page to show the same node with its same comment but
    // with a different display mode.
    $this->drupalGet($this->node
        ->toUrl());
    // The comment should exist but without the body text because we used $mode
    // mode this time.
    $comment_element = $this->cssSelect('#comment-1');
    $this->assertNotEmpty($comment_element);
    $this->assertSession()
        ->responseNotContains('<p>' . $comment_text . '</p>');
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.