drupal 7 ajax form重建表单来改变form_state值

时间:2014-02-22 10:04:11

标签: drupal-7 drupal-forms drupal-ajax

我有一个drupal表单,我希望它可以作为“再添加一个”:表单末尾有一个按钮,单击它时,另一个表单将附加到它。这是我的代码的一部分:

function add_passenger_form($form, &$form_state){
   if(!isset($form_state['num_names'])){
      $form_state['num_names']=2;
   }
   $form['add_button']= array(
    '#type' => 'button',
    '#value'=> 'Add more',
    '#ajax' => array(
        'callback' => 'ajax_add_passenger_callback',
        'method' => 'replace',
        'effect' => 'fade',
        'wrapper' => 'last_field',
    ),
  );
  $form['form_number']=array(
        '#prefix'=>'<div class="form_number">',
        '#suffix'=>'</div>',
        '#type'=>'hidden',
        '#value'=>2,
    );
}

function ajax_add_passenger_callback($form, &$form_state){
    $form_state['num_names']++;
$form_state['rebuild']=TRUE;
    $form['form_number']['#value']=$form_state['num_names'];
    return array(
                    '#type' => 'ajax',
                    '#commands' => array(
                                    ajax_command_replace(".form_number", render($form['form_number'])),

                    )
                );
}

当我点击添加一个按钮时,我希望$ form ['num_names'] ['#value']增加一个。现在它只能工作一次(到3)。

2 个答案:

答案 0 :(得分:2)

像这样更改你的代码..这将创建按钮“添加更多”以为每位乘客添加新乘客和一个字段(名称)。您可以将“名称”字段替换为例如fieldset,并为一名乘客添加更多字段。

function add_passenger_form($form, &$form_state){

   if(!isset($form_state['num_names'])){
      $form_state['num_names']=2;
   }

   // Create wrapper for ajax
   $form['#prefix'] = '<div id="form-wrapper">';
   $form['#suffix'] = '</div>';

   for ($i = 0; $i < $form_state['num_names']; $i++) {  

     $form['name_' . $i] = array(
       '#type' => 'textfield',
       '#title' => t('Name'),
       '#required' => true
     ); 
   }

   $form['add_button']= array(
    '#type' => 'button',
    '#value'=> 'Add more',
    '#ajax' => array(
        'callback' => 'ajax_add_passenger_callback',
        'method' => 'replace',
        'effect' => 'fade',
        'wrapper' => 'form-wrapper',
    ),
  );
}

function ajax_add_passenger_callback($form, &$form_state){

    $form_state['num_names']++;

    // rebuild whole form with new values
    $form_state['rebuild'] = true;
}

另请查看此链接以获取有关ajax的更多信息:

https://api.drupal.org/api/examples/ajax_example!ajax_example_graceful_degradation.inc/7

答案 1 :(得分:0)

<?php
include 'db.php';
if(isset($_POST['search'])) {
    $_POST['stYear'] = array_key_exists('stYear', $_POST) ? mysqli_real_escape_string($con, $_POST['stYear']) : null;
    if (empty($_POST['stYear'])) {
        exit('Invalid year given');
    }
    $sql = "SELECT * FROM socio WHERE year ='$input'";
    $res = mysqli_query($con, $sql) or die($sql);
    while ($row = mysqli_fetch_array($res)) {
        echo 'You selected '.$input;
    }
    mysqli_close($con);
}