问题是 Locale 模块在调用 hook_form_alter() 之后改变了这个表单元素(参见这篇文章)。
这是我解决这个问题的方法:
首先,更改 Drupal 实现其钩子的顺序,将“form_alter”放在最后一个:
<?php
/**
* Implementation of hook_module_implements_alter()
*/
function chronos_module_implements_alter(&$implementations, $hook) {
if ($hook == 'form_alter') {
// Move mymodule_form_alter() to the end of the list. module_implements()
// iterates through $implementations with a foreach loop which PHP iterates
// in the order that the items were added, so to move an item to the end of
// the array, we remove it and then add it.
$group = $implementations['chronos'];
unset($implementations['chronos']);
$implementations['chronos'] = $group;
}
}
接下来,在 $form['language'] 上添加一个表单元素和你想要的 '#ajax' 元素:
<?php
/**
* Implements hook_form_alter().
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'page_node_form') {
// alter the form
$form['container'] = array(
'#prefix' => '<div id="ajax-language">',
'#suffix' => '</div>',
);
$form['language']['#ajax'] = array(
'callback' => 'mymodule_save_language_callback',
'wrapper' => 'ajax-language'
);
return $form;
}
}
最后,添加您的回调:
<?php
/**
* Returns changed part of the form.
*
* @return renderable array
*
* @see ajax_example_form_node_form_alter()
*/
function chronos_save_language_callback($form, $form_state) {
# set session variables or perform other actions here, if applicable
return $form['container'];
}