function CommentForm::save

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

Overrides EntityForm::save

File

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

Class

CommentForm
Base handler for comment forms.

Namespace

Drupal\comment

Code

public function save(array $form, FormStateInterface $form_state) {
    $comment = $this->entity;
    $entity = $comment->getCommentedEntity();
    $is_new = $this->entity
        ->isNew();
    $field_name = $comment->getFieldName();
    $uri = $entity->toUrl();
    $logger = $this->logger('comment');
    if ($this->currentUser
        ->hasPermission('post comments') && ($this->currentUser
        ->hasPermission('administer comments') || $entity->{$field_name}->status == CommentItemInterface::OPEN)) {
        $comment->save();
        $form_state->setValue('cid', $comment->id());
        // Add a log entry.
        $logger->info('Comment posted: %subject.', [
            '%subject' => $comment->getSubject(),
            'link' => Link::fromTextAndUrl(t('View'), $comment->toUrl()
                ->setOption('fragment', 'comment-' . $comment->id()))
                ->toString(),
        ]);
        // Add an appropriate message upon submitting the comment form.
        $this->messenger()
            ->addStatus($this->getStatusMessage($comment, $is_new));
        $query = [];
        // Find the current display page for this comment.
        $field_definition = $this->entityFieldManager
            ->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$field_name];
        $page = $this->entityTypeManager
            ->getStorage('comment')
            ->getDisplayOrdinal($comment, $field_definition->getSetting('default_mode'), $field_definition->getSetting('per_page'));
        if ($page > 0) {
            $query['page'] = $page;
        }
        // Redirect to the newly posted comment.
        $uri->setOption('query', $query);
        $uri->setOption('fragment', 'comment-' . $comment->id());
    }
    else {
        $logger->warning('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', [
            '%subject' => $comment->getSubject(),
        ]);
        $this->messenger()
            ->addError($this->t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', [
            '%subject' => $comment->getSubject(),
        ]));
        // Redirect the user to the entity they are commenting on.
    }
    $form_state->setRedirectUrl($uri);
}

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