对Drupal 7表单中填充选项的文本字段进行计数


Count textfields filled to populate options in a select input in Drupal 7 form

我希望能够计算已填充的文本输入的数量,并使用结果创建带有选项0-[count returned]的下拉列表。我用的是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);
}

谢谢

这似乎是为我现在工作,相同的方法,但使用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);
}