Drupal 7 在Drupal7上被难住了-通过hook_form#alter添加用户配置文件_form#验证回调
我搜索、阅读、再阅读。我甚至把一个测试模块剥离到了最基本的元素 我认为这段代码应该可以工作,但是从来没有调用过验证回调。我将回调添加到表单中,但在接下来的步骤中它将消失 最终,我的目标是“验证”提交的用户名,以满足特定的业务目标。我在添加表单验证回调时遇到了困难,但我相信,一旦克服了这一障碍,其余的功能就会迎刃而解 能不能请比我聪明的人给我指出正确的方向来正确添加验证回调Drupal 7 在Drupal7上被难住了-通过hook_form#alter添加用户配置文件_form#验证回调,drupal-7,hook-form-alter,drupal-form-validation,Drupal 7,Hook Form Alter,Drupal Form Validation,我搜索、阅读、再阅读。我甚至把一个测试模块剥离到了最基本的元素 我认为这段代码应该可以工作,但是从来没有调用过验证回调。我将回调添加到表单中,但在接下来的步骤中它将消失 最终,我的目标是“验证”提交的用户名,以满足特定的业务目标。我在添加表单验证回调时遇到了困难,但我相信,一旦克服了这一障碍,其余的功能就会迎刃而解 能不能请比我聪明的人给我指出正确的方向来正确添加验证回调 <?php /* Implements hook_form_alter(); */ function mymo
<?php
/*
Implements hook_form_alter();
*/
function mymod_form_alter($form, $form_state, $form_id) {
// catch the user profile form.
if('user_profile_form' == $form_id) {
// set debug message
drupal_set_message(t('adding validation callback in hook_form_alter()...'), 'warning');
// add a validation callback
$form['#validate'][] = 'mymod_user_profile_form_validate';
}
}
/*
Implements hook_form_<form_id>_alter();
If mymod_form_alter() was successful, I wouldn't need this hook, it's just here for verification.
*/
function mymod_form_user_profile_form_alter($form, $form_state, $form_id) {
// check to see if our validation callback is present
if(!in_array('mymod_user_profile_form_validate', $form['#validate'])) {
// our validatiation callback is not present
drupal_set_message(t('The validation callback is missing from #validate in hook_form_[form_id]_alter()'), 'error');
// since it's not there, try re-adding it?
$form['#validate'][] = 'mymod_user_profile_form_validate';
} else {
// We should see this message, but don't.
drupal_set_message(t('The validation callback exists!'), 'status');
}
}
/*
?? Implements hook_form_validate(); (or not...) ??
*/
function mymod_user_profile_form_validate($form, $form_state) {
// why is mymod_user_profile_form_validate() never called??
drupal_set_message(t('Validation callback called! Whoopee! Success!'), 'status'); // This never happens!
// if this was working, we would do a bit of logic here on the username.
//for this test, let's assume we want to return an error on the username field.
form_set_error('name', t('Blah, blah, blah, something about your username...'));
}
变量$form
和$form\u state
应该是这样的,以便钩子函数可以实际修改它们(否则函数只需获得一个副本)
您需要使用函数签名中变量参数之前添加的&
(与号)符号:
function mymod_form_alter(&$form, &$form_state, $form_id) {
# $form is referenced from the global scope using '&' symbol
$form['#validate'][] = 'mymod_user_profile_form_validate';
}
感谢您的解释,包括通过参考链接!这正是我所需要的!