setAuthorName example


    // Empty author ID should revert to anonymous.     $author_id = $form_state->getValue('uid');
    if ($comment->id() && $this->currentUser->hasPermission('administer comments')) {
      // Admin can leave the author ID blank to revert to anonymous.       $author_id = $author_id ?: 0;
    }
    if (!is_null($author_id)) {
      if ($author_id === 0 && $form['author']['name']['#access']) {
        // Use the author name value when the form has access to the element and         // the author ID is anonymous.         $comment->setAuthorName($form_state->getValue('name'));
      }
      else {
        // Ensure the author name is not set.         $comment->setAuthorName(NULL);
      }
    }
    else {
      $author_id = $this->currentUser->id();
    }
    $comment->setOwnerId($author_id);

    
    $this->assertNotContains(0, array_map('strlen', $tests), 'No empty tokens generated.');

    foreach ($tests as $input => $expected) {
      $bubbleable_metadata = new BubbleableMetadata();
      $output = $token_service->replace($input['comment' => $comment]['langcode' => $language_interface->getId()]$bubbleable_metadata);
      $this->assertSame((string) $expected(string) $output, "Failed test case: {$input}");
      $this->assertEquals($metadata_tests[$input]$bubbleable_metadata);
    }

    // Test anonymous comment author.     $author_name = 'This is a random & " > string';
    $comment->setOwnerId(0)->setAuthorName($author_name);
    $input = '[comment:author]';
    $output = $token_service->replace($input['comment' => $comment]['langcode' => $language_interface->getId()]);
    $this->assertSame((string) Html::escape($author_name)(string) $output);
    // Add comment field to user and term entities.     $this->addDefaultCommentField('user', 'user', 'comment', CommentItemInterface::OPEN, 'comment_user');
    $this->addDefaultCommentField('taxonomy_term', 'tags', 'comment', CommentItemInterface::OPEN, 'comment_term');

    // Create a user and a comment.     $user = User::create(['name' => 'alice']);
    $user->activate();
    $user->save();
    
Home | Imprint | This part of the site doesn't use cookies.