You are here

11 钩子hook_block_view

admin 的头像
Submitted by admin on 星期五, 2015-06-26 09:52

作者:老葛,北京亚艾元软件有限责任公司,http://www.yaiyuan.com

通过使用Drupal函数variable_set(),我们将帖子数量和基路径的配置保存了下来。最后添加hook_block_view的实现,当区块显示时,返回Discuz最新帖子:

 

/**

 * 实现钩子hook_block_view().

 */

function discuz_topics_block_view($delta = '') {

  $block = array();

 

  switch ($delta) {

    case 'topics':

      $block['subject'] = t('论坛最新帖子');

      $block['content'] = discuz_topics_get_recent_topics();

      break;

  }

  return $block;

}

 

    在这里我们使用$block['subject']设置区块的默认标题,使用$block['content']设置区块的内容,我们将区块内容的显示委托给了discuz_topics_get_recent_topics函数,这样使得hook_block_view钩子中的代码逻辑更加清晰一点。现在让我们看看这个函数:

 

/**

 * 区块内容的回调函数.

 */

function discuz_topics_get_recent_topics(){

  $output = "";

  $num = variable_get('discuz_topics_num', 5);

  $base_url=variable_get('discuz_topics_base_url','http://localhost/discuz');

 

  $query = Database::getConnection('default', 'discuz')

->select('posts', 'p')

->fields('p', array('tid', 'subject'))

->condition('p.first', 1, '=')

->range(0, $num)

->orderBy('p.pid','DESC');

 

  $result = $query->execute();

  $output .= "<ul class='discuz-topics'>";

  foreach ($result as $record) { 

    $output .= '<li>';

   $output .= l($record->subject,$base_url.'/viewthread.php?tid='.$record->tid);

    $output .= '</li>';

//drupal_set_message($record->subject);

  }

  $output .= "</ul>";

  return $output;

}

这里,我们通过对Discuz数据库进行查询,来获取里面的最新帖子,将帖子标题显示为链接形式,这样点击这个链接,就会自动地进入对应的论坛帖子页面了。将区块启用后,效果如图所示:

图片1.png 

图“论坛最新帖子”区块实际效果图

    

    在一个模块中,我们可以定义多个区块,只需要使用delta标识判断即可,我们在这里只用这么一个作为例子。


Drupal版本: