用户登录

Drupal资源链接

http://zhupou.cn
drupal布道者,改成了"老葛的Drupal培训班",专心于培训事业
http://drupal.org
官方网站
http://drupalchina.org
中文的官方网站
http://acquia.com/
本站就是用这个版本构建的

触发器动作和hook

在这一章中主要讲叙了在drupal中的hook,trigger和action动作之间的关系。

为什么会有trigger和action呢?

例如:我希望在insert comment,或者insert user时都显示:你好,谢谢加入,那么用模块编写很容易做到这一点.

/*输入你好谢谢加入*/
function beep(){
    drupal_set_message("你好,谢谢加入", 'status',  TRUE);
}
/*hook_user*/
function beep_user($op, &$edit, &$account, $category = NULL){
    global $user;
    if ($op=='insert'){
        beep()
    }
}
/*hook_comment*/
function beep_comment($op, &$edit){
    global $user;
    if ($op=='insert'){
        beep()
    }
}

但如果我还要在加入节点也要这个提示,那么还要hook_nodeapi,如果编写hook_nodeapi,如果想在分类时也要的话,那要编写更多的内容,有没有一种简便的方法,因为所有的操作都  一样,只显示一个"你好,谢谢加入"。在drupal中的解决之道就是使用action.通过编写一个动作,然后使用trigger界面,将动作分配给不同的触发器。

/*hook_action_info定义一个动作,在启用trigger模块之后,将在action中看到动作*/
function beep_action_info() {
$info['beep_action'] = array(
    'type' => 'system',
    'description' => t('发送一个消息'),
    'configurable' => FALSE,
    'hooks' => array(
        any=>TRUE,
        ),
);
return $info;
}
/*定义动作*/
function beep_action() {
      beep();   
}

在模块安装时我使用了这个actions_synchronize()命令,这个是同步action的,否则好象动作不会马上显示出来 。

那么在trigge中我们可以自由将这个动作分配不同的hook.方便用户的使用。

高级动作,是指可配置的动作,将 'configurable' => TRUE,其中hooks数组可以设置hook的内容,如'nodeapi' => array('view', 'insert', 'update', 'delete'),'comment' => array('view', 'insert', 'update', 'delete'),'user' => array('view', 'insert', 'update', 'delete', 'login'),
'taxonomy' => array('insert', 'update', 'delete'),如果是全部的话any=>TRUE.

还有应该设置高级动作的表单,

/**
* Form for configurable Drupal action to beep multiple times.
*/
function beep_multiple_beep_action_form($context) {
$form['beeps'] = array(
'#type' => 'textfield',
'#title' => t('Number of beeps'),
'#description' => t('Enter the number of times to beep when this action
executes.'),
'#default_value' => isset($context['beeps']) ? $context['beeps'] : '1',
'#required' => TRUE,
);
return $form;
}
function beep_multiple_beep_action_validate($form, $form_state) {
$beeps = $form_state['values']['beeps'];
if (!is_numeric($beeps)) {
form_set_error('beeps', t('Please enter a numeric value.'));
}
else if ((int) $beeps > 10) {
form_set_error('beeps', t('That would be too annoying. Please choose fewer
than 10 beeps.'));
}
}
function beep_multiple_beep_action_submit($form, $form_state) {
return array(
'beeps' => (int) $form_state['values']['beeps']
);
}

不通过trigger,可以直接用actions_do($action_ids, &$object, $context = array(), $a1 = NULL, $a2 = NULL)来执行某个动作。

还可以用hook_hook_info还hook trigger,增加触发器,但令人困惑的是,用hook_hook_info,增加触发器之后,分配动作却不坐执行,可能是我某个地方搞错了,还是....