是否有方法绑定一个ajax回调时,语言发生了变化,我想更新一个noderreference -下拉菜单时,语言发生了变化(以显示值仅在该语言)。
下面的代码不工作(form_alter),尽管其他回调正在工作。
谁能帮我怎么才能做到这一点?
$form['language']['#ajax'] = array(
'callback' => 'mymodule_something_language_callback',
'wrapper' => 'my-module-replace',
'#weight' => 2
);
谢谢。从评论
$form['language'];
array
'#type' => string 'select' (length=6)
'#title' => string 'Language' (length=8)
'#default_value' => string 'und' (length=3)
'#options' =>
array
'und' => string 'Language neutral' (length=16)
'en' => string 'English' (length=7)
'ar' => string 'Arabic' (length=6)
问题是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'];
}