计算填充的文本字段以填充Drupal 7表单中的选择输入中的选项

时间:2014-06-11 11:05:53

标签: php jquery ajax forms drupal-7

我希望能够计算已填充的文本输入的数量,并使用结果创建下拉选项0- [计数返回]。我正在使用 Drupal 7中的ajax_command_replace函数,但对任何其他方法的建议都是开放的。

我有一个测试,它会对填充的输入进行计数并显示结果,但我无法弄清楚如何使用它来填充选择。

任何帮助都非常感激。

表单元素。

$array = array_fill(0,5,'');

$form['test'] = array(
'#type'=> 'fieldset',
'#title' => 'TEST',
);
$form['test']['value']['#tree'] = TRUE;

foreach ($array as $key => $value) {
$form['test']['value'][$key] = array(
    '#type' => 'textfield',
    '#ajax' => array(
      'callback' => 'test_callback',

    ),
);

}
$test = count(array_filter($array));
$form['test']['count'] = array(

    '#suffix' => "<div id='testcount'>filled inputs = $test</div>",
);

和ajax回调

function test_callback($form, $form_state){
    $text = count(array_filter($form_state['input']['value']));

    $commands = array();
    $commands[] = ajax_command_replace("#testcount", "<div id='testcount'>filled inputs = $text</div>");
    return array('#type' => 'ajax', '#commands' => $commands);
}

由于

1 个答案:

答案 0 :(得分:0)

现在这似乎对我有用,同样的方法,但使用render()函数从回调中返回更新的表单元素。我希望它可以帮助别人。

$array = array_fill(0,5,'');

                $form['test'] = array(
                    '#type'=> 'fieldset',
                    '#title' => 'TEST',
                );
                $form['test']['value']['#tree'] = TRUE;

                foreach ($array as $key => $value) {
                    $form['test']['value'][$key] = array(
                        '#type' => 'textfield',
                        '#ajax' => array(
                            'callback' => 'test_callback',                      
                        ),
                    );

                }
                $options = range(count(array_filter($array)),0,1);
                $form['test']['count'] = array(
                    '#type'=> 'select',
                    '#options' => $options,
                    '#prefix' => '<div id="testcount">',
                    '#suffix' => "</div>",

                );

回调

function test_callback($form, $form_state){
$text = count(array_filter($form_state['input']['value']));
$default = $form_state['input']['count'];
$options = range($text,0,1);
$form['test']['count'] = array(
    '#type'=> 'select',
    '#options' => $options,
    '#prefix' => '<div id="testcount">',
    '#suffix' => "</div>",
    '#default_value' => $default,
);

   $commands = array();
   $commands[] = ajax_command_replace("#testcount", render($form['test']['count']));

   return array('#type' => 'ajax', '#commands' => $commands);
}