You are here

public function HeartbeatCommentForm::commentAjaxSubmit in Heartbeat 8

File

src/Form/HeartbeatCommentForm.php, line 68

Class

HeartbeatCommentForm
Class HeartbeatCommentForm.

Namespace

Drupal\heartbeat\Form

Code

public function commentAjaxSubmit(array &$form, FormStateInterface $form_state) {
  if (\Drupal::currentUser()
    ->isAuthenticated()) {
    $commentBody = $form_state
      ->getValue('comment_body');
    $config = \Drupal::config('heartbeat_comment.settings');
    if (strlen(trim($commentBody)) > 1) {
      $extraMarkup = null;
      $sharedUrls = array_values($this->markupGenerator
        ->validateUrl($commentBody))[0];
      if (!empty($sharedUrls)) {
        $url = !is_array($sharedUrls) ? $sharedUrls : array_values($sharedUrls)[0];
        $this->markupGenerator
          ->parseMarkup($url);
        $extraMarkup = '<a href="' . $url . '" class="status-comment-share"> ' . $this->markupGenerator
          ->generatePreview() . '</a>';
      }
      $comment = Comment::create([
        'entity_type' => 'heartbeat',
        'entity_id' => $config
          ->get('entity_id'),
        'field_name' => 'comment',
        'comment_body' => [
          'value' => $commentBody . $extraMarkup,
          'format' => 'basic_html',
        ],
        'comment_type' => 'comment',
        'subject' => 'Heartbeat Comment',
        'uid' => \Drupal::currentUser()
          ->id(),
      ]);
      if ($comment
        ->save()) {
        $userview = user_view($comment
          ->getOwner(), 'comment');
        $cid = $comment
          ->id();
        $body = $commentBody;
        $response = new AjaxResponse();
        $response
          ->addCommand(new PrependCommand('#heartbeat-' . $config
          ->get('entity_id') . ' .heartbeat-comments', '<div id="heartbeat-comment-' . $comment
          ->id() . '"><span class="comment-owner"><span class="comment-username">' . \Drupal::currentUser()
          ->getAccountName() . '</span>' . render($userview) . '<span class"comment-ago">1 sec ago</span></span><span class="comment-body">' . $commentBody . '</span><span class="sub-comment"><a href="/heartbeat/subcommentrequest/' . $cid . '" class="button button-action use-ajax">Reply</a></span></div>'));
        return $response;
      }
    }
  }
  return null;
}