先看实现的效果:
在某些情况下,我们会需要接管用户注册功能。比如这里,我就会需要系统生成一个顺序号作为用户名,然后随机生成一个密码。也就是说,注册过程是不需要用户人工干预的(captcha是另外一个话题)。
我们需要做的,是接管user_register这个form:
function signup_form_user_register_alter(&$form, &$form_state) {}
这里signup就是module的名字,而user_regsiter是form的id,这个函数会在user_reister这个form被build的时候自动调用,我们所要做的就是干掉这个表单中的东西:
// we are about to rewrite the whole register form
unset($form['mail']);
unset($form['name']);
unset($form['pass']);
当然,干掉这里边的的东西还是不够的,我们还需要添加自己的东西:
$form['ucategory'] = array(
'#type' => 'radios',
'#required' => TRUE,
'#options' => array(
'0' => t('I\'m a student of CCOM, and would like to take a secondary profession.'),
'1' => t('I\'m a student inside China mainland.'),
'2' => t('I\'m a Chinese student located in Hong Kong, Macau, Taiwan or outside China.'),
'3' => t('I\'m a foreigner.'),
),
'#default_value' => '1',
);
最重要的一件事,就是接管validate事件和submit事件:
$form['#validate'] = array();
$form['#submit'] = array('signup_form_user_register_submit');
因为我这里的form比较简单,所以不需要validate,把validate直接置空会省事很多。而submit函数里可以用来生成我需要的用户名和密码:
function signup_form_user_register_submit($form, &$form_state) {
$data=array();
// Now generating the ID number of the student
$sid_prev=db_result(db_query('SELECT MAX(name) FROM {users} WHERE name like \'2008B%\''));
$data['name']=sprintf('2008B%04d',substr($sid_prev,6)+1);
// Generate a radom password at 6 bit
$data['pass']=user_password(6);
$data['status']=1;
$data['mail']=signup_get_random_mail_address();
// Create the user !
$user=user_save('',$data);
// Thanks god, we could output the username and password via message
drupal_set_message(t('Your ID is @name, password is @pass',array('@name'=>$data['name'], '@pass'=>$data['pass'])));
// We need to fill up more information after login
user_authenticate($data);
$form_state['redirect']='user/'.$user->uid.'/edit';
}
这里的具体算法只是为了演示如何接管Drupal的注册系统。这个例子已经在实际中投入使用。其中的代码,经过少许修改,也应该可以在Drupal5中使用,有心人可以试试。
| 附件 | 大小 |
|---|---|
| drupal_register_take_over.PNG | 14.9 KB |
评论
赞
HOOK设计模式就是赞