I would like to have some advice about my preprocess function i made this morning.

My goals was to replace the name by the role of the author in a comment.

I have many questions because i think my code isn't optimize and i would like to improve it:

  • I don't know, as a beginner, if it's better to do what i want to achieve in a module or in a preprocess function?
  • I used this path to change the comment author name : $variables['author'] It works but is it this variable we have to use if we want to alter the comment author.
  • I made my request inside my preprocess function, is it good to do that? I have only few comments for now, but when i'll have hundred of comments, do you think i'll have a problem of performance? Is there a way to improve it?

    function bartik_extended_preprocess_comment(&$variables) {       
     $result = db_query("SELECT users.uid AS uid, role.name AS  role_name
                  FROM {users} users
                  LEFT JOIN {users_roles} roles_id 
                    ON (( (users.uid = roles_id.uid ) ))
                  LEFT JOIN {role} role  
                     ON (( (roles_id.rid = role.rid ) ))
                  WHERE (( (users.uid = :uid ) ))", array(':uid' => $variables['elements']['#comment']->uid));
    $store = array();
    foreach ($result as $row) {
      $store['uid'] = $row -> uid;
      $store['role'] = $row -> role_name;
    if($variables['elements']['#comment']->uid == $store['uid']) {
       $variables['author'] = check_plain($store['role']);



1 Answer 1

  1. Module VS preprocess function - modules can use preprocess functions as well. I guess that the question in your case is whether or not to do the changes in a custom module or theme. It's up to you, but generally speaking, keep the specific UI improvements in the theme and let the module do the hard work you will need in any case (if you change the theme for example). Also, it's better to pack the things you might need somewhere else in a module as it's easier to drop it to another site.

  2. You can load the user object with user_load($uid);. This will also load all roles with role IDs and names. I suggest installing Devel and calling dpm($user); to have a better understanding of what you get in the user object.

  3. If by request you mean database request - yes, it's alright, if there's not a way to do so already. As I mentioned in 2. you can use user_load function - this will reduce the code and also load the user object from cache. I think that Drupal already called user_load for rendering the comments, so calling it again will just get everything from cache and won't impact performance.

Hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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