Question

My comments on articles have a required Fivestar rating field called 'Stars' and I hid it with the following custom module (see: https://drupal.stackexchange.com/questions/90629/how-to-hide-rating-field-when-adding-comment-to-own-node):

function hiderating_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == "comment_node_article_form") {
   if ($form['#node']->uid == $user->uid) { 
      unset($form['field_stars']);
    }
  }
}

As an administrator, I've permission to edit comments from other users. Suppose that a user commented on his own article. That means he didn't have to set the 'Stars' field, due to the code above. But when I try to edit that comment, I do have to select a value for the 'Stars'.

How can I prevent this? It's sufficient to check that the uid from the user who wrote the comment differs from the uid from the user who edits the comment. Finally, mark that the obligation to select stars when I leave a new comment myself must be preserved!


Edit: I tried the following code:

function hiderating_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  $comment->uid = $form_state['values']['uid'];
  if ($form_id == "comment_node_article_form") {
   if ($comment->uid != $user->uid) { 
    unset($form['field_stars']);
    }
  }
}

Apparently, $form_state['values'] isn't well defined, because I get the following error:

"Notice: Undefined index: values in hiderating_form_alter()".

What's the correct code?

Was it helpful?

Solution

The code in the edit doesn't work, because $form_state['values'] isn't present before the submit. This is the correct code:

function hiderating_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == "comment_node_article_form") {
   if ($form['uid']['#value'] != $user->uid AND $form['uid']['#value'] != 0) { 
    unset($form['field_stars']);
   }
  }
}

Using dpm($form), I discovered that $form['uid']['#value'] returns the uid from the user who wrote the comment. The value is only different from 0 if a comment is edited. When a user writes a new comment, the uid from the form is 0. That's why the AND in the second if is necessary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top