5

I'm trying to make the comment author name required with this code:

use Drupal\Core\Form\FormStateInterface;
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_comment_comment_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $form['name']['#required'] = true;
}

But I can't find the way to do so. How to make the comment author name required for anonymous users?

2 Answers 2

3

You can try:

if (\Drupal::currentUser()->isAnonymous()) {
  $form['author']['name']['#required'] = TRUE;
}

It is necessary because it is not right to check if user is authenticated by checking if the name field is prefilled.

We have to use \Drupal::currentUser() service in theme or module file (in controller you have to use Drupal\Core\Session\AccountProxy).

currentUser() Documentation

/**
 * Implements hook_form_FORM_ID_alter().
 */

function MODULE_form_comment_comment_form_alter(array &$form, FormStateInterface $form_state, $form_id) 
{
  if (\Drupal::currentUser()->isAnonymous()) {
    $form['author']['name']['#required'] = TRUE;
  }
  else {
    $form['author']['name']['#required'] = FALSE;
  }
}
2
  • I'd argue that the if check is unnecessary - if the user is logged in the name field is prefilled anyway making the method proposed by Adrian marginally quicker. Commented Nov 21, 2016 at 16:38
  • As a note for this - I'm saying it's essentially redundant to check that the user is logged in as if they are logged in the required field is prefilled. With that said @AndrewNim's method is probably a more "Drupal" method of doing this. Plus a possibly-redundant if is preferrable to an error. Commented Nov 21, 2016 at 16:50
10

I found the answer:

Implementing the hook_form_FORM_ID_alter() hook you can use the comment form id (comment_comment_form) to alter the form.

The problem was that the field name is inside the author, so you need to use $form['author']['name']['#required'] = TRUE;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_comment_comment_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $form['author']['name']['#required'] = TRUE;
}
3
  • 2
    @Pierre.Vriens I edit the answer, if you see any problem feel free to edit. Commented Nov 21, 2016 at 15:27
  • @AdrianCidAlmaguer your edits look good to me - the explanation does make it clearer. Commented Nov 21, 2016 at 15:29
  • @HomoTechsual thanks, if you want edit the answer feel free too Commented Nov 21, 2016 at 15:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.