【问题标题】:Drupal Form APi Checkbox statesDrupal Form APi 复选框状态
【发布时间】:2011-10-26 08:27:27
【问题描述】:

所以我在表单中创建了我的复选框

$form['existing_customer'] = array(
    '#type' => 'checkbox',
    '#title' => t('Are you an existing customer'),
    '#ajax' => array(
    'callback' => 'checkbox_selected',
    'wrapper' => 'subject',
),);

这会调用我的函数并更改复选框中的值

问题是如果未选中,我无法让它切换回来

function checkbox_selected(&$form, &$form_state) {
    if ($form_state['values']['existing_customer'] == 1) {

        $my_options = array( 'select' => t('Select'), 'mr' => t('Mr'), 'mrs' => t('Mrs'), 'miss' => t('Miss'), 'ms' =>t('Ms'), 'sir' =>t('Sir'), 'dr' => t('Dr'), 'prof' => t('Prof') );

    }
    elseif ($form_state['values']['existing_customer'] == 0){
        $my_options = array( 'seconfZ' => t('jimmy'), 'mr' => t('Mr'), );

    }
    $form['subject'] = array(
        '#type' => 'select',
        '#title' => t('Subject'),
        '#options' => $my_options//$form['subject_options']['#value']
    );
    return $form['subject'];
}

我以为我可以对复选框值或状态进行切换,但没有乐趣?

【问题讨论】:

  • 你的回调真的被调用了吗?我没有将“回调”视为表单 API 中的属性,但确实看到了“#value_callback”
  • 它被调用了,“#value_callback”是什么意思?
  • 你用的是什么版本?我通常将此用作参考,而那是我没有看到它的地方,因此我不确定您的方法是否被调用,以及如果调用它应该返回什么。 api.drupal.org/api/drupal/…

标签: ajax forms api drupal checkbox


【解决方案1】:

通常,当您使用 Form API #ajax 系统时,在元素包装器上再次调用 drupal_html_id() 之后,您指定的 wrapper 实际上会被另一个元素替换。所以我会在你的 AJAX 事情发生后检查 Firebug/Web Inspector 中“主题”元素的标记——我打赌包装器 div 现在类似于“主题--1”。

要解决此问题,您需要在要替换的项目上手动设置一个包装器 div——在重建表单时不会更改该包装器 div。例如,在您的表单构建器中:

$form['existing_customer'] = array(
  '#type' => 'checkbox',
  '#title' => t('Are you an existing customer'),
  '#ajax' => array(
    'callback' => 'checkbox_selected',
    'wrapper' => 'subject-wrapper',
  ),
);
$form['subject'] = array(
  '#prefix' => '<div id="subject-wrapper">',
  ...
  `#suffix' => '</div>',
);

希望有帮助!

【讨论】:

  • 我记得那个问题。我想我使用了一个非常老套的修复方法解决了这个问题,但这似乎是一个很可能的解决方案。将其添加书签以供参考,我很快就会做一些表格。
猜你喜欢
  • 2011-10-22
  • 1970-01-01
  • 2023-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-27
相关资源
最近更新 更多