annotate_node-1.0.1-alpha1/src/Form/CommentForm.php
src/Form/CommentForm.php
<?php namespace Drupal\annotate_node\Form; use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; use Drupal\comment\Entity\Comment; use Drupal\Core\Ajax\AjaxResponse; use Drupal\Core\Ajax\AppendCommand; use Drupal\Component\Utility\Xss; /** * */ class CommentForm extends FormBase { /** * {@inheritdoc} */ public function getFormId() { return 'comment_form'; } /** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $form['title'] = [ '#type' => 'textfield', '#title' => $this->t('Subject'), '#maxlength' => 64, ]; $form['comment'] = [ '#type' => 'text_format', '#title' => $this->t(''), ]; $form['paragraph_number'] = [ '#type' => 'textfield', '#title' => $this->t('paragraph_number'), '#format' => 'full_html', ]; $form['actions'] = [ '#type' => 'button', '#value' => $this->t('Submit'), '#ajax' => [ 'callback' => '::insertComment', ] ]; return $form; } /** * {@inheritdoc} */ public function insertComment(array $form, FormStateInterface $form_state) { $config = \Drupal::config('annotate_node.settings'); $string_separate = $config->get('string_separate'); $node = \Drupal::routeMatch()->getParameter('node'); if ($string_separate == 'Paragraphs') { $paragraph_sentence = 'p'; } else { $paragraph_sentence = 's'; } $paragraph_number = $form_state->getValue('paragraph_number'); $comment_body = $form_state->getValue('comment')['value']; $uid = \Drupal::currentUser()->id(); // Need to strip the <p> tag that CKE adds for messes up formatting of comments. $tags = ["<p>", "</p>", "<font>", "</font>"]; $comment_body = str_replace($tags, "", $comment_body); $values = [ 'entity_type' => 'node', 'entity_id' => $node->id(), 'field_name' => 'field_comments_manually', 'uid' => $uid, 'comment_type' => 'annotate_node_comment', 'subject' => $form_state->getValue('title'), 'comment_body' => $form_state->getValue('comment')['value'], 'paragraph_number' => $form_state->getValue('paragraph_number'), 'paragraph_sentence' => $paragraph_sentence, 'status' => 1, ]; $comment = Comment::create($values); $comment->save(); $messenger = \Drupal::messenger(); $messenger->addMessage($config->get('annotation_confirmation'), $messenger::TYPE_STATUS); $paragraph_number = Xss::filter($paragraph_number); $comment_body = Xss::filter($comment_body); $response = new AjaxResponse(); $response->addCommand( new AppendCommand( '#comments-' . $paragraph_number . '', '<div><span class="commentDate">' . date("F jS Y h:i:s") . '</span></div><p class="separate-cmt" id="comment-' . $paragraph_number . '-temp">' . $comment_body . '</p>' ) ); return $response; } /** * {@inheritdoc} * * Using Ajax and calling insertComment function instead. */ public function submitForm(array &$form, FormStateInterface $form_state) { } }