使注册用户在发表评论时可设置昵称

  Drupal 的评论功能,默认可以配置成允许匿名用户填写联系信息,使匿名用户可以使用任意昵称发表评论。而 Drupal 注册用户,在登录之后,默认只能使用用户名进行回复,无法像匿名用户那样使用任意昵称。

  本文通过创建一个简单的 Drupal 模块,为拥有 set comment name 权限的登录用户,能够在发布评论时手动设置昵称。

创建模块文件夹: sites/all/modules/comment_name

创建模块信息文件:在comment_name模块目录下创建模块信息文件, comment_name.info,并将以下内容写入到 comment_name.info 文件中

name = "Comment Name"
description = "Let authenticated user post comments as an anomyouse user with a name."
core = 6.x
package = Other
dependencies[] = comment

创建模块文件:在 comment_name 目录下创建 comment_name.module 文件,将以下内容写入到 comment_name.module 文件中

<?php
/**
 * Implementation of hook_perm().
 */
function comment_name_perm() {
  return array(
'set comment name');
}


/**
 * Implementation of hook_form_alert().
 */
function comment_name_form_alter(&$form$form_state$form_id) {
 
//dsm($form);
 
  
global $user;
  
  if (
$form_id == 'comment_form' && $user->uid != && (user_access('set comment name') || $user->uid == 1) ) {
            
    
// add comment name textfield
    
$form['comment_name'] = array(
      
'#type' => 'textfield'
      
'#title' => t('Authored by'), 
      
'#size' => 30
      
'#maxlength' => 60
      
'#default_value' => ''
      
'#weight' => -1,
    );
    
  }
  
}


/**
 * Implementation of hook_comment().
 */
function comment_name_comment(&$comment$op) {

  switch (
$op) {
    
    case 
'view':
      
// When comment load, use comment_name value replace username
      
$_comment _comment_load($comment->cid);
      
$comment->name $_comment->name;
      break;
      
    case 
'insert':
      
// After comment saved, use comment_name value replace username
      
$query "UPDATE {comments} SET name = '%s' WHERE cid = %d";
      
db_query($query$comment['comment_name'], $comment['cid']);
      break;
      
  }
  
}


?>

启用模块:访问 管理 > 站点构建 > 模块(admin/build/modules)页面,启用 Comment Name 模块

设置权限:访问 管理 > 用户管理 > 权限(admin/user/permissions)页面,为指定的用户角色启用 set comment name 权限

  完成以上操作之后,访问某个可评论的节点,拥有 set comment name 权限用户和 Drupal 管理员在发布评论时就能够以匿名用户的身份,使用任意名称发表评论了。