function CommentForm::buildEntity

Same name and namespace in other branches
  1. 9 core/modules/comment/src/CommentForm.php \Drupal\comment\CommentForm::buildEntity()
  2. 8.9.x core/modules/comment/src/CommentForm.php \Drupal\comment\CommentForm::buildEntity()
  3. 11.x core/modules/comment/src/CommentForm.php \Drupal\comment\CommentForm::buildEntity()

Overrides ContentEntityForm::buildEntity

File

core/modules/comment/src/CommentForm.php, line 290

Class

CommentForm
Base handler for comment forms.

Namespace

Drupal\comment

Code

public function buildEntity(array $form, FormStateInterface $form_state) {
  /** @var \Drupal\comment\CommentInterface $comment */
  $comment = parent::buildEntity($form, $form_state);
  if (!$form_state->isValueEmpty('date') && $form_state->getValue('date') instanceof DrupalDateTime) {
    $comment->setCreatedTime($form_state->getValue('date')
      ->getTimestamp());
  }
  else {
    $comment->setCreatedTime($this->time
      ->getRequestTime());
  }
  // 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);
  // Validate the comment's subject. If not specified, extract from comment
  // body.
  if (trim($comment->getSubject()) == '') {
    if ($comment->hasField('comment_body') && !$comment->comment_body
      ->isEmpty()) {
      // The body may be in any format, so:
      // 1) Filter it into HTML
      // 2) Strip out all HTML tags
      // 3) Convert entities back to plain-text.
      $comment_text = $comment->comment_body->processed;
      $comment->setSubject(Unicode::truncate(trim(Html::decodeEntities(strip_tags($comment_text))), 29, TRUE, TRUE));
    }
    // Edge cases where the comment body is populated only by HTML tags will
    // require a default subject.
    if (trim($comment->getSubject()) == '') {
      $comment->setSubject($this->t('(No subject)'));
    }
  }
  return $comment;
}

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