3 namespace Drupal\comment;
5 use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
6 use Drupal\Component\Datetime\TimeInterface;
7 use Drupal\Component\Utility\Html;
8 use Drupal\Component\Utility\Unicode;
9 use Drupal\Core\Datetime\DrupalDateTime;
10 use Drupal\Core\Entity\ContentEntityForm;
11 use Drupal\Core\Entity\EntityConstraintViolationListInterface;
12 use Drupal\Core\Entity\EntityFieldManagerInterface;
13 use Drupal\Core\Entity\EntityRepositoryInterface;
14 use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
15 use Drupal\Core\Form\FormStateInterface;
16 use Drupal\Core\Render\RendererInterface;
17 use Drupal\Core\Session\AccountInterface;
18 use Symfony\Component\DependencyInjection\ContainerInterface;
21 * Base handler for comment forms.
25 class CommentForm extends ContentEntityForm {
30 * @var \Drupal\Core\Session\AccountInterface
32 protected $currentUser;
37 * @var \Drupal\Core\Render\RendererInterface
42 * The entity field manager.
44 * @var \Drupal\Core\Entity\EntityFieldManagerInterface
46 protected $entityFieldManager;
51 public static function create(ContainerInterface $container) {
53 $container->get('entity.repository'),
54 $container->get('current_user'),
55 $container->get('renderer'),
56 $container->get('entity_type.bundle.info'),
57 $container->get('datetime.time'),
58 $container->get('entity_field.manager')
63 * Constructs a new CommentForm.
65 * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
66 * The entity repository.
67 * @param \Drupal\Core\Session\AccountInterface $current_user
69 * @param \Drupal\Core\Render\RendererInterface $renderer
71 * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
72 * The entity type bundle service.
73 * @param \Drupal\Component\Datetime\TimeInterface $time
76 public function __construct(EntityRepositoryInterface $entity_repository, AccountInterface $current_user, RendererInterface $renderer, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL, EntityFieldManagerInterface $entity_field_manager = NULL) {
77 parent::__construct($entity_repository, $entity_type_bundle_info, $time);
78 $this->currentUser = $current_user;
79 $this->renderer = $renderer;
80 $this->entityFieldManager = $entity_field_manager ?: \Drupal::service('entity_field.manager');
86 public function form(array $form, FormStateInterface $form_state) {
87 /** @var \Drupal\comment\CommentInterface $comment */
88 $comment = $this->entity;
89 $entity = $this->entityTypeManager->getStorage($comment->getCommentedEntityTypeId())->load($comment->getCommentedEntityId());
90 $field_name = $comment->getFieldName();
91 $field_definition = $this->entityFieldManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$comment->getFieldName()];
92 $config = $this->config('user.settings');
94 // In several places within this function, we vary $form on:
95 // - The current user's permissions.
96 // - Whether the current user is authenticated or anonymous.
97 // - The 'user.settings' configuration.
98 // - The comment field's definition.
99 $form['#cache']['contexts'][] = 'user.permissions';
100 $form['#cache']['contexts'][] = 'user.roles:authenticated';
101 $this->renderer->addCacheableDependency($form, $config);
102 $this->renderer->addCacheableDependency($form, $field_definition->getConfig($entity->bundle()));
104 // Use #comment-form as unique jump target, regardless of entity type.
105 $form['#id'] = Html::getUniqueId('comment_form');
106 $form['#theme'] = ['comment_form__' . $entity->getEntityTypeId() . '__' . $entity->bundle() . '__' . $field_name, 'comment_form'];
108 $anonymous_contact = $field_definition->getSetting('anonymous');
109 $is_admin = $comment->id() && $this->currentUser->hasPermission('administer comments');
111 if (!$this->currentUser->isAuthenticated() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT) {
112 $form['#attached']['library'][] = 'core/drupal.form';
113 $form['#attributes']['data-user-info-from-browser'] = TRUE;
116 // If not replying to a comment, use our dedicated page callback for new
117 // Comments on entities.
118 if (!$comment->id() && !$comment->hasParentComment()) {
119 $form['#action'] = $this->url('comment.reply', ['entity_type' => $entity->getEntityTypeId(), 'entity' => $entity->id(), 'field_name' => $field_name]);
122 $comment_preview = $form_state->get('comment_preview');
123 if (isset($comment_preview)) {
124 $form += $comment_preview;
127 $form['author'] = [];
128 // Display author information in a details element for comment moderators.
131 '#type' => 'details',
132 '#title' => $this->t('Administration'),
136 // Prepare default values for form elements.
139 if (!$comment->getOwnerId()) {
140 $author = $comment->getAuthorName();
142 $status = $comment->getStatus();
143 if (empty($comment_preview)) {
144 $form['#title'] = $this->t('Edit comment %title', [
145 '%title' => $comment->getSubject(),
150 $status = ($this->currentUser->hasPermission('skip comment approval') ? CommentInterface::PUBLISHED : CommentInterface::NOT_PUBLISHED);
154 if ($comment->id()) {
155 $date = !empty($comment->date) ? $comment->date : DrupalDateTime::createFromTimestamp($comment->getCreatedTime());
158 // The uid field is only displayed when a user with the permission
159 // 'administer comments' is editing an existing comment from an
160 // authenticated user.
161 $owner = $comment->getOwner();
162 $form['author']['uid'] = [
163 '#type' => 'entity_autocomplete',
164 '#target_type' => 'user',
165 '#default_value' => $owner->isAnonymous() ? NULL : $owner,
166 // A comment can be made anonymous by leaving this field empty therefore
167 // there is no need to list them in the autocomplete.
168 '#selection_settings' => ['include_anonymous' => FALSE],
169 '#title' => $this->t('Authored by'),
170 '#description' => $this->t('Leave blank for %anonymous.', ['%anonymous' => $config->get('anonymous')]),
171 '#access' => $is_admin,
174 // The name field is displayed when an anonymous user is adding a comment or
175 // when a user with the permission 'administer comments' is editing an
176 // existing comment from an anonymous user.
177 $form['author']['name'] = [
178 '#type' => 'textfield',
179 '#title' => $is_admin ? $this->t('Name for @anonymous', ['@anonymous' => $config->get('anonymous')]) : $this->t('Your name'),
180 '#default_value' => $author,
181 '#required' => ($this->currentUser->isAnonymous() && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
183 '#access' => $this->currentUser->isAnonymous() || $is_admin,
186 'data-drupal-default-value' => $config->get('anonymous'),
191 // When editing a comment only display the name textfield if the uid field
193 $form['author']['name']['#states'] = [
195 ':input[name="uid"]' => ['empty' => TRUE],
200 // Add author email and homepage fields depending on the current user.
201 $form['author']['mail'] = [
203 '#title' => $this->t('Email'),
204 '#default_value' => $comment->getAuthorEmail(),
205 '#required' => ($this->currentUser->isAnonymous() && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
208 '#description' => $this->t('The content of this field is kept private and will not be shown publicly.'),
209 '#access' => ($comment->getOwner()->isAnonymous() && $is_admin) || ($this->currentUser->isAnonymous() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
212 $form['author']['homepage'] = [
214 '#title' => $this->t('Homepage'),
215 '#default_value' => $comment->getHomepage(),
218 '#access' => $is_admin || ($this->currentUser->isAnonymous() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
221 // Add administrative comment publishing options.
222 $form['author']['date'] = [
223 '#type' => 'datetime',
224 '#title' => $this->t('Authored on'),
225 '#default_value' => $date,
227 '#access' => $is_admin,
230 $form['author']['status'] = [
232 '#title' => $this->t('Status'),
233 '#default_value' => $status,
235 CommentInterface::PUBLISHED => $this->t('Published'),
236 CommentInterface::NOT_PUBLISHED => $this->t('Not published'),
238 '#access' => $is_admin,
241 return parent::form($form, $form_state, $comment);
247 protected function actions(array $form, FormStateInterface $form_state) {
248 $element = parent::actions($form, $form_state);
249 /* @var \Drupal\comment\CommentInterface $comment */
250 $comment = $this->entity;
251 $entity = $comment->getCommentedEntity();
252 $field_definition = $this->entityManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$comment->getFieldName()];
253 $preview_mode = $field_definition->getSetting('preview');
255 // No delete action on the comment form.
256 unset($element['delete']);
258 // Mark the submit action as the primary action, when it appears.
259 $element['submit']['#button_type'] = 'primary';
261 // Only show the save button if comment previews are optional or if we are
262 // already previewing the submission.
263 $element['submit']['#access'] = ($comment->id() && $this->currentUser->hasPermission('administer comments')) || $preview_mode != DRUPAL_REQUIRED || $form_state->get('comment_preview');
265 $element['preview'] = [
267 '#value' => $this->t('Preview'),
268 '#access' => $preview_mode != DRUPAL_DISABLED,
269 '#submit' => ['::submitForm', '::preview'],
278 public function buildEntity(array $form, FormStateInterface $form_state) {
279 /** @var \Drupal\comment\CommentInterface $comment */
280 $comment = parent::buildEntity($form, $form_state);
281 if (!$form_state->isValueEmpty('date') && $form_state->getValue('date') instanceof DrupalDateTime) {
282 $comment->setCreatedTime($form_state->getValue('date')->getTimestamp());
285 $comment->setCreatedTime(REQUEST_TIME);
287 // Empty author ID should revert to anonymous.
288 $author_id = $form_state->getValue('uid');
289 if ($comment->id() && $this->currentUser->hasPermission('administer comments')) {
290 // Admin can leave the author ID blank to revert to anonymous.
291 $author_id = $author_id ?: 0;
293 if (!is_null($author_id)) {
294 if ($author_id === 0 && $form['author']['name']['#access']) {
295 // Use the author name value when the form has access to the element and
296 // the author ID is anonymous.
297 $comment->setAuthorName($form_state->getValue('name'));
300 // Ensure the author name is not set.
301 $comment->setAuthorName(NULL);
305 $author_id = $this->currentUser->id();
307 $comment->setOwnerId($author_id);
309 // Validate the comment's subject. If not specified, extract from comment
311 if (trim($comment->getSubject()) == '') {
312 if ($comment->hasField('comment_body')) {
313 // The body may be in any format, so:
314 // 1) Filter it into HTML
315 // 2) Strip out all HTML tags
316 // 3) Convert entities back to plain-text.
317 $comment_text = $comment->comment_body->processed;
318 $comment->setSubject(Unicode::truncate(trim(Html::decodeEntities(strip_tags($comment_text))), 29, TRUE, TRUE));
320 // Edge cases where the comment body is populated only by HTML tags will
321 // require a default subject.
322 if ($comment->getSubject() == '') {
323 $comment->setSubject($this->t('(No subject)'));
332 protected function getEditedFieldNames(FormStateInterface $form_state) {
333 return array_merge(['created', 'name'], parent::getEditedFieldNames($form_state));
339 protected function flagViolations(EntityConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {
340 // Manually flag violations of fields not handled by the form display.
341 foreach ($violations->getByField('created') as $violation) {
342 $form_state->setErrorByName('date', $violation->getMessage());
344 foreach ($violations->getByField('name') as $violation) {
345 $form_state->setErrorByName('name', $violation->getMessage());
347 parent::flagViolations($violations, $form, $form_state);
351 * Form submission handler for the 'preview' action.
354 * An associative array containing the structure of the form.
355 * @param \Drupal\Core\Form\FormStateInterface $form_state
356 * The current state of the form.
358 public function preview(array &$form, FormStateInterface $form_state) {
359 $comment_preview = comment_preview($this->entity, $form_state);
360 $comment_preview['#title'] = $this->t('Preview comment');
361 $form_state->set('comment_preview', $comment_preview);
362 $form_state->setRebuild();
368 public function save(array $form, FormStateInterface $form_state) {
369 $comment = $this->entity;
370 $entity = $comment->getCommentedEntity();
371 $field_name = $comment->getFieldName();
372 $uri = $entity->urlInfo();
373 $logger = $this->logger('comment');
375 if ($this->currentUser->hasPermission('post comments') && ($this->currentUser->hasPermission('administer comments') || $entity->{$field_name}->status == CommentItemInterface::OPEN)) {
377 $form_state->setValue('cid', $comment->id());
380 $logger->notice('Comment posted: %subject.', [
381 '%subject' => $comment->getSubject(),
382 'link' => $this->l(t('View'), $comment->urlInfo()->setOption('fragment', 'comment-' . $comment->id())),
385 // Explain the approval queue if necessary.
386 if (!$comment->isPublished()) {
387 if (!$this->currentUser->hasPermission('administer comments')) {
388 $this->messenger()->addStatus($this->t('Your comment has been queued for review by site administrators and will be published after approval.'));
392 $this->messenger()->addStatus($this->t('Your comment has been posted.'));
395 // Find the current display page for this comment.
396 $field_definition = $this->entityFieldManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$field_name];
397 $page = $this->entityTypeManager->getStorage('comment')->getDisplayOrdinal($comment, $field_definition->getSetting('default_mode'), $field_definition->getSetting('per_page'));
399 $query['page'] = $page;
401 // Redirect to the newly posted comment.
402 $uri->setOption('query', $query);
403 $uri->setOption('fragment', 'comment-' . $comment->id());
406 $logger->warning('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', ['%subject' => $comment->getSubject()]);
407 $this->messenger()->addError($this->t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', ['%subject' => $comment->getSubject()]));
408 // Redirect the user to the entity they are commenting on.
410 $form_state->setRedirectUrl($uri);