我制作了一个自定义模块,在其中创建了一个页面。在该页面中,我加载现有表单以创建新内容并添加密码字段。在我加载的表单中,我有一个电子邮件字段。我想在提交表单之前检查是否存在用户名、在电子邮件字段中找到的值以及密码字段提供的密码的用户。这里我有3个场景:
- 如果用户不存在,我将获取电子邮件和密码并创建一个帐户,然后创建内容
- 如果用户存在并且密码正确,我创建内容
- 如果用户存在但密码不正确,我将停止表单提交
我的问题是我不知道如何停止表单提交(我指的是场景编号 3)。任何建议都是最有价值的
以下是页面函数的回调:
function add_new_article_simple_page() {
module_load_include('inc', 'node', 'node.pages');
$node_form = new stdClass;
$node_form->type = 'announcement';
$node_form->language = LANGUAGE_NONE;
$form = drupal_get_form('announcement_node_form', $node_form);
return $form;
}
插入密码字段的 alter 函数:
function add_new_article_form_alter(&$form, &$form_state, $form_id){
if($form_id=='announcement_node_form')
{
$form['#after_build'][] = 'add_new_article_after_build';
$form['account_password'] = array(
'#title' => 'Parola',
'#type' => 'password',
'#required' => TRUE,
);
$form['#submit'][] = 'add_new_article_form_submit';
return $form;
}
}
和表单提交功能
function add_new_article_form_submit($form, &$form_state){
$email=$form_state['values']['field_email']['und'][0]['value'];
$password=$form_state['values']['account_password'];
//check if the email even exists
if(!db_query("SELECT COUNT(*) FROM {users} WHERE name = '".$email."';")->fetchField())
//create the new account
{
$edit = array(
'name' => $email,
'pass' => $password,
'mail' => $email,
'init' => $email,
'roles' => array('4' => 'standard user'),
'status' => 0,
'access' => REQUEST_TIME,
);
$loc_var=user_save(drupal_anonymous_user(), $edit);
$GLOBALS['new_user']=$loc_var->uid;
}
else
{
//check if username + password are valid combination
if($uid = user_authenticate($email,$password))
//log in user after account creation
else
//this is where I want to interrupt the submission of the form
form_set_error('account_password', 'Parola nu este buna pentru acest email.');
}
}
更新
我的错,我忘了解释当我测试第三种情况时会发生什么。内容已创建,页面跳转到该内容页面,这就是错误消息出现的地方
更新 2 我遵循了 D34dman 的建议并编写了一个简单的验证函数,它应该总是给出一个错误。问题是内容仍然提交并保存。它似乎甚至没有调用 hook_form_validate .. 这是函数:
function add_new_article_form_validate($form, &$form_state)
{
$email=$form_state['values']['field_email']['und'][0]['value'];
$password=$form_state['values']['account_password'];
form_set_error('account_password',t('The form is being validated.'.$email.' and '.$password));
}
谢谢你,克里斯蒂