Drupal: remove "your name" elements from comment form

Drupal

Unfortunately, Drupal displays the user name for the logged in user above the comment input field. It is entirely unnecessary so I wanted to remove it. Of course, you could revert to CSS but to me, that is not a solution, you're just hiding the label and data.

There is a Drupal post "Hiding comment form fields" with a snippet (best placed in a custom module) to remove access to the "your name" elements:

<?php
function mymodule_form_comment_form_alter(&$form, &$form_state) {

 
$form['author']['#access'] = FALSE;

}
?>

You could add this hook to a custom module so it will be valid regardless of the theme you are using. However, I opted to move this code to phptemplate.php for my theme.

Since I wanted to hide the data for anonymous users only, I could have used the $user variable and test with: $user->uid but I find that rather ugly:

<?php
function YOURTHEME_form_comment_form_alter(&$form, &$form_state) {

 
/* Remove the "your name" elements for authenticated users */
 
global $user;
 
$form['author']['#access'] = ($user->uid == 0);

}
?>

(Although Drupal's user_is_anonymous() and user_is_logged_in() are doing this.)

Looking at the DEVEL tab for a post, I saw how the author name is displayed:

and similarly, how there is an element called is_anonymous (bottom of screendump):

So why not create the following code:

<?php
function YOURTHEME_form_comment_form_alter(&$form, &$form_state) {

 
/* Remove the "your name" elements for authenticated users */
 
$form['author']['#access'] = $form['is_anonymous']['#value'];

}
?>

Clean solution. Now the "your name" will be hidden for authenticated users, but not for anonymous users:

Mission accomplished.

Edit Dec 21, 2014

I ran into a snag with this solution. If a user has the "administer comments" permission the administrative fieldset is visible. This is tested in comment.module with: <?php $is_admin = (!empty($comment->cid) && user_access('administer comments')); ?>.

Normally, the administrative fieldset is visible:

But if the comment author name is not visible the fieldset is not visible either when editing a comment from a user:

In order to work around this, I changed the template.php code to test for the edit argument:

<?php
function MYTHEME_form_comment_form_alter(&$form, &$form_state) {

 
// Remove the author field for authenticated users (when not editing comment)
 
if ($form['is_anonymous']['#value'] == false && arg(2) != 'edit') {
   
$form['author']['#access'] = false;
  }

}
?>

Comments

Thanks for sharing, that's what I was looking for and wasn't aware of is_anonymous

I didn't know either, it's worth peeking at the devel screens.

Great post

very useful. thanks a bunch!

Thanks !!! After 2 days of trying, your solutions worked! +1

Thanks! After 2 days, it finally works !