2

有没有办法在更改语言时绑定 ajax 回调,我想在更改语言时更新 nodereference-dropdown(仅显示该语言的值)。

尽管其他回调正在工作,但以下代码不起作用(form_alter)。

有人可以帮助我如何实现这一目标吗?

$form['language']['#ajax'] = array(
            'callback' => 'mymodule_something_language_callback',
            'wrapper' => 'my-module-replace',                
            '#weight' => 2
        );

谢谢。

来自评论

继承人 $form['language']; 的 var_dump

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)
4

1 回答 1

0

问题是 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'];
}
于 2014-09-17T21:46:47.393 回答