CommentForm::buildEntity

public CommentForm::buildEntity(array $form, FormStateInterface $form_state)

Builds an updated entity object based upon the submitted form values.

For building the updated entity object the form's entity is cloned and the submitted form values are copied to entity properties. The form's entity remains unchanged.

Parameters

array $form: A nested array form elements comprising the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

\Drupal\Core\Entity\EntityInterface An updated copy of the form's entity object.

Overrides ContentEntityForm::buildEntity

See also

\Drupal\Core\Entity\EntityFormInterface::getEntity()

File

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

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(REQUEST_TIME);
  }
  // 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')) {
      // 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 ($comment->getSubject() == '') {
      $comment->setSubject($this->t('(No subject)'));
    }
  }
  return $comment;
}
doc_Drupal
2016-10-29 08:50:40
Comments
Leave a Comment

Please login to continue.