You are here

class CommentForm in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/comment/src/CommentForm.php \Drupal\comment\CommentForm

Base handler for comment forms.

@internal

Hierarchy

Expanded class hierarchy of CommentForm

File

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

Namespace

Drupal\comment
View source
class CommentForm extends ContentEntityForm {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * The renderer.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * The entity field manager.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity.repository'), $container
      ->get('current_user'), $container
      ->get('renderer'), $container
      ->get('entity_type.bundle.info'), $container
      ->get('datetime.time'), $container
      ->get('entity_field.manager'));
  }

  /**
   * Constructs a new CommentForm.
   *
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
   *   The entity repository.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer.
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
   *   The entity type bundle service.
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The time service.
   */
  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) {
    parent::__construct($entity_repository, $entity_type_bundle_info, $time);
    $this->currentUser = $current_user;
    $this->renderer = $renderer;
    $this->entityFieldManager = $entity_field_manager ?: \Drupal::service('entity_field.manager');
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {

    /** @var \Drupal\comment\CommentInterface $comment */
    $comment = $this->entity;
    $entity = $this->entityTypeManager
      ->getStorage($comment
      ->getCommentedEntityTypeId())
      ->load($comment
      ->getCommentedEntityId());
    $field_name = $comment
      ->getFieldName();
    $field_definition = $this->entityFieldManager
      ->getFieldDefinitions($entity
      ->getEntityTypeId(), $entity
      ->bundle())[$comment
      ->getFieldName()];
    $config = $this
      ->config('user.settings');

    // In several places within this function, we vary $form on:
    // - The current user's permissions.
    // - Whether the current user is authenticated or anonymous.
    // - The 'user.settings' configuration.
    // - The comment field's definition.
    $form['#cache']['contexts'][] = 'user.permissions';
    $form['#cache']['contexts'][] = 'user.roles:authenticated';
    $this->renderer
      ->addCacheableDependency($form, $config);
    $this->renderer
      ->addCacheableDependency($form, $field_definition
      ->getConfig($entity
      ->bundle()));

    // Use #comment-form as unique jump target, regardless of entity type.
    $form['#id'] = Html::getUniqueId('comment_form');
    $form['#theme'] = [
      'comment_form__' . $entity
        ->getEntityTypeId() . '__' . $entity
        ->bundle() . '__' . $field_name,
      'comment_form',
    ];
    $anonymous_contact = $field_definition
      ->getSetting('anonymous');
    $is_admin = $comment
      ->id() && $this->currentUser
      ->hasPermission('administer comments');
    if (!$this->currentUser
      ->isAuthenticated() && $anonymous_contact != CommentInterface::ANONYMOUS_MAYNOT_CONTACT) {
      $form['#attached']['library'][] = 'core/drupal.form';
      $form['#attributes']['data-user-info-from-browser'] = TRUE;
    }

    // If not replying to a comment, use our dedicated page callback for new
    // Comments on entities.
    if (!$comment
      ->id() && !$comment
      ->hasParentComment()) {
      $form['#action'] = Url::fromRoute('comment.reply', [
        'entity_type' => $entity
          ->getEntityTypeId(),
        'entity' => $entity
          ->id(),
        'field_name' => $field_name,
      ])
        ->toString();
    }
    $comment_preview = $form_state
      ->get('comment_preview');
    if (isset($comment_preview)) {
      $form += $comment_preview;
    }
    $form['author'] = [];

    // Display author information in a details element for comment moderators.
    if ($is_admin) {
      $form['author'] += [
        '#type' => 'details',
        '#title' => $this
          ->t('Administration'),
      ];
    }

    // Prepare default values for form elements.
    $author = '';
    if ($is_admin) {
      if (!$comment
        ->getOwnerId()) {
        $author = $comment
          ->getAuthorName();
      }
      $status = $comment
        ->isPublished() ? CommentInterface::PUBLISHED : CommentInterface::NOT_PUBLISHED;
      if (empty($comment_preview)) {
        $form['#title'] = $this
          ->t('Edit comment %title', [
          '%title' => $comment
            ->getSubject(),
        ]);
      }
    }
    else {
      $status = $this->currentUser
        ->hasPermission('skip comment approval') ? CommentInterface::PUBLISHED : CommentInterface::NOT_PUBLISHED;
    }
    $date = '';
    if ($comment
      ->id()) {
      $date = !empty($comment->date) ? $comment->date : DrupalDateTime::createFromTimestamp($comment
        ->getCreatedTime());
    }

    // The uid field is only displayed when a user with the permission
    // 'administer comments' is editing an existing comment from an
    // authenticated user.
    $owner = $comment
      ->getOwner();
    $form['author']['uid'] = [
      '#type' => 'entity_autocomplete',
      '#target_type' => 'user',
      '#default_value' => $owner
        ->isAnonymous() ? NULL : $owner,
      // A comment can be made anonymous by leaving this field empty therefore
      // there is no need to list them in the autocomplete.
      '#selection_settings' => [
        'include_anonymous' => FALSE,
      ],
      '#title' => $this
        ->t('Authored by'),
      '#description' => $this
        ->t('Leave blank for %anonymous.', [
        '%anonymous' => $config
          ->get('anonymous'),
      ]),
      '#access' => $is_admin,
    ];

    // The name field is displayed when an anonymous user is adding a comment or
    // when a user with the permission 'administer comments' is editing an
    // existing comment from an anonymous user.
    $form['author']['name'] = [
      '#type' => 'textfield',
      '#title' => $is_admin ? $this
        ->t('Name for @anonymous', [
        '@anonymous' => $config
          ->get('anonymous'),
      ]) : $this
        ->t('Your name'),
      '#default_value' => $author,
      '#required' => $this->currentUser
        ->isAnonymous() && $anonymous_contact == CommentInterface::ANONYMOUS_MUST_CONTACT,
      '#maxlength' => 60,
      '#access' => $this->currentUser
        ->isAnonymous() || $is_admin,
      '#size' => 30,
      '#attributes' => [
        'data-drupal-default-value' => $config
          ->get('anonymous'),
      ],
    ];
    if ($is_admin) {

      // When editing a comment only display the name textfield if the uid field
      // is empty.
      $form['author']['name']['#states'] = [
        'visible' => [
          ':input[name="uid"]' => [
            'empty' => TRUE,
          ],
        ],
      ];
    }

    // Add author email and homepage fields depending on the current user.
    $form['author']['mail'] = [
      '#type' => 'email',
      '#title' => $this
        ->t('Email'),
      '#default_value' => $comment
        ->getAuthorEmail(),
      '#required' => $this->currentUser
        ->isAnonymous() && $anonymous_contact == CommentInterface::ANONYMOUS_MUST_CONTACT,
      '#maxlength' => 64,
      '#size' => 30,
      '#description' => $this
        ->t('The content of this field is kept private and will not be shown publicly.'),
      '#access' => $comment
        ->getOwner()
        ->isAnonymous() && $is_admin || $this->currentUser
        ->isAnonymous() && $anonymous_contact != CommentInterface::ANONYMOUS_MAYNOT_CONTACT,
    ];
    $form['author']['homepage'] = [
      '#type' => 'url',
      '#title' => $this
        ->t('Homepage'),
      '#default_value' => $comment
        ->getHomepage(),
      '#maxlength' => 255,
      '#size' => 30,
      '#access' => $is_admin || $this->currentUser
        ->isAnonymous() && $anonymous_contact != CommentInterface::ANONYMOUS_MAYNOT_CONTACT,
    ];

    // Add administrative comment publishing options.
    $form['author']['date'] = [
      '#type' => 'datetime',
      '#title' => $this
        ->t('Authored on'),
      '#default_value' => $date,
      '#size' => 20,
      '#access' => $is_admin,
    ];
    $form['author']['status'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Status'),
      '#default_value' => $status,
      '#options' => [
        CommentInterface::PUBLISHED => $this
          ->t('Published'),
        CommentInterface::NOT_PUBLISHED => $this
          ->t('Not published'),
      ],
      '#access' => $is_admin,
    ];
    return parent::form($form, $form_state, $comment);
  }

  /**
   * {@inheritdoc}
   */
  protected function actions(array $form, FormStateInterface $form_state) {
    $element = parent::actions($form, $form_state);

    /* @var \Drupal\comment\CommentInterface $comment */
    $comment = $this->entity;
    $entity = $comment
      ->getCommentedEntity();
    $field_definition = $this->entityFieldManager
      ->getFieldDefinitions($entity
      ->getEntityTypeId(), $entity
      ->bundle())[$comment
      ->getFieldName()];
    $preview_mode = $field_definition
      ->getSetting('preview');

    // No delete action on the comment form.
    unset($element['delete']);

    // Mark the submit action as the primary action, when it appears.
    $element['submit']['#button_type'] = 'primary';

    // Only show the save button if comment previews are optional or if we are
    // already previewing the submission.
    $element['submit']['#access'] = $comment
      ->id() && $this->currentUser
      ->hasPermission('administer comments') || $preview_mode != DRUPAL_REQUIRED || $form_state
      ->get('comment_preview');
    $element['preview'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Preview'),
      '#access' => $preview_mode != DRUPAL_DISABLED,
      '#submit' => [
        '::submitForm',
        '::preview',
      ],
    ];
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  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;
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditedFieldNames(FormStateInterface $form_state) {
    return array_merge([
      'created',
      'name',
    ], parent::getEditedFieldNames($form_state));
  }

  /**
   * {@inheritdoc}
   */
  protected function flagViolations(EntityConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {

    // Manually flag violations of fields not handled by the form display.
    foreach ($violations
      ->getByField('created') as $violation) {
      $form_state
        ->setErrorByName('date', $violation
        ->getMessage());
    }
    foreach ($violations
      ->getByField('name') as $violation) {
      $form_state
        ->setErrorByName('name', $violation
        ->getMessage());
    }
    parent::flagViolations($violations, $form, $form_state);
  }

  /**
   * Form submission handler for the 'preview' action.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function preview(array &$form, FormStateInterface $form_state) {
    $comment_preview = comment_preview($this->entity, $form_state);
    $comment_preview['#title'] = $this
      ->t('Preview comment');
    $form_state
      ->set('comment_preview', $comment_preview);
    $form_state
      ->setRebuild();
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $comment = $this->entity;
    $entity = $comment
      ->getCommentedEntity();
    $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
        ->notice('Comment posted: %subject.', [
        '%subject' => $comment
          ->getSubject(),
        'link' => Link::fromTextAndUrl(t('View'), $comment
          ->toUrl()
          ->setOption('fragment', 'comment-' . $comment
          ->id()))
          ->toString(),
      ]);

      // Explain the approval queue if necessary.
      if (!$comment
        ->isPublished()) {
        if (!$this->currentUser
          ->hasPermission('administer comments')) {
          $this
            ->messenger()
            ->addStatus($this
            ->t('Your comment has been queued for review by site administrators and will be published after approval.'));
        }
      }
      else {
        $this
          ->messenger()
          ->addStatus($this
          ->t('Your comment has been posted.'));
      }
      $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);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CommentForm::$currentUser protected property The current user.
CommentForm::$entityFieldManager protected property The entity field manager.
CommentForm::$renderer protected property The renderer.
CommentForm::actions protected function Returns an array of supported actions for the current entity form. Overrides EntityForm::actions
CommentForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides ContentEntityForm::buildEntity
CommentForm::create public static function Instantiates a new instance of this class. Overrides ContentEntityForm::create
CommentForm::flagViolations protected function Flags violations for the current form. Overrides ContentEntityForm::flagViolations
CommentForm::form public function Gets the actual form array to be built. Overrides ContentEntityForm::form
CommentForm::getEditedFieldNames protected function Gets the names of all fields edited in the form. Overrides ContentEntityForm::getEditedFieldNames
CommentForm::preview public function Form submission handler for the 'preview' action.
CommentForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
CommentForm::__construct public function Constructs a new CommentForm. Overrides ContentEntityForm::__construct
ContentEntityForm::$entity protected property The entity being used by this form. Overrides EntityForm::$entity 9
ContentEntityForm::$entityRepository protected property The entity repository service.
ContentEntityForm::$entityTypeBundleInfo protected property The entity type bundle info service.
ContentEntityForm::$time protected property The time service.
ContentEntityForm::addRevisionableFormFields protected function Add revision form fields if the entity enabled the UI.
ContentEntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties Overrides EntityForm::copyFormValuesToEntity
ContentEntityForm::getBundleEntity protected function Returns the bundle entity of the entity, or NULL if there is none.
ContentEntityForm::getFormDisplay public function Gets the form display. Overrides ContentEntityFormInterface::getFormDisplay
ContentEntityForm::getFormLangcode public function Gets the code identifying the active form language. Overrides ContentEntityFormInterface::getFormLangcode
ContentEntityForm::getNewRevisionDefault protected function Should new revisions created on default.
ContentEntityForm::init protected function Initializes the form state and the entity before the first form build. Overrides EntityForm::init 1
ContentEntityForm::initFormLangcodes protected function Initializes form language code values.
ContentEntityForm::isDefaultFormLangcode public function Checks whether the current form language matches the entity one. Overrides ContentEntityFormInterface::isDefaultFormLangcode
ContentEntityForm::prepareEntity protected function Prepares the entity object before the form is built first. Overrides EntityForm::prepareEntity 1
ContentEntityForm::setFormDisplay public function Sets the form display. Overrides ContentEntityFormInterface::setFormDisplay
ContentEntityForm::showRevisionUi protected function Checks whether the revision form fields should be added to the form.
ContentEntityForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides EntityForm::submitForm 3
ContentEntityForm::updateChangedTime public function Updates the changed time of the entity.
ContentEntityForm::updateFormLangcode public function Updates the form language to reflect any change to the entity language.
ContentEntityForm::validateForm public function Button-level validation handlers are highly discouraged for entity forms, as they will prevent entity validation from running. If the entity is going to be saved during the form submission, this method should be manually invoked from the button-level… Overrides FormBase::validateForm 3
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::__get public function
EntityForm::__set public function
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.