在最近的项目中,我通过创建一个新的菜单回调(例如类似)实现了类似的功能,该菜单回调example.com/anon_user
提供了兼用作登录名和注册表的形式。这使用户可以非常快速地完成注册过程或登录,而无需使他们执行过多的操作。实际上,它收到的还不错。
以下是一些简化的代码来演示这一点:
function example_form($form, &$form_state) {
// Don't let authenticated users use this form.
global $user;
if ($user->uid != 0) {
return MENU_ACCESS_DENIED;
}
// Let the user know what they can do.
$form['intro']['#markup'] = "Already have an account? Login here. Don't have an account? Enter your email address and create a password and we'll setup an account for you.");
$form['login'] = array(
'#type' => 'fieldset',
'user_email' => array(
'#type' => 'textfield',
'#required' => TRUE,
'#title' => t('E-mail Address'),
),
'user_pass' => array(
'#type' => 'password',
'#required' => TRUE,
'#title' => t('Password'),
),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Continue',
);
return $form;
}
验证它,但是您需要:
function example_form_validate(&$form, &$form_state) {
if (!valid_email_address($form_state['values']['user_email'])) {
form_set_error('user_email', 'You entered an invalid email address.');
}
}
在提交处理程序中,我们需要确定此电子邮件是否已经存在并尝试登录。如果不存在,请尝试为其创建一个帐户。
function example_form_submit(&$form, &$form_state) {
global $user;
// Does this account already exist?
if ($user_name = db_query("SELECT name FROM {users} WHERE mail = :mail", array(':mail' => $form_state['values']['user_email']))->fetchField()) {
// Attempt to log them in.
if ($account_id = user_authenticate($user_name, $form_state['values']['user_pass'])) {
drupal_set_message('You have been logged in.');
$user = user_load($account_id);
} else {
drupal_set_message('You have an account here, but you entered the wrong password.', 'error');
}
}
// Create the account.
else {
// Use their email address as their username. Or handle this with a more complex login form.
$account_name = str_replace('@', '_', $form_state['values']['user_email']);
$account = user_save(null, array(
'name' => $account_name,
'pass' => $form_state['values']['user_pass'],
'mail' => $form_state['values']['user_email'],
'init' => $form_state['values']['user_email'],
'status' => 1,
'access' => REQUEST_TIME,
));
// Log 'em in to their new account.
drupal_set_message('Your account has been created and you have been successfully logged in!');
);
$user = user_load(user_authenticate($account->name, $form_state['values']['user_pass']));
}
}
这是一个非常简单的示例。您可以添加密码要求,通过第二个字段的密码确认,用户名字段,更好的警告等。更多的限制会延长过程,因此请记住这一点。