drupaldrupal-7drupal-formsdrupal-ajax

Drupal 7, how to dynamically populate a field based on the summation of two other fields?


I have two fields

$form["field_num_males"]
$form["field_num_females"]

I need to dynamically populate the field $form["field_gender_total"] with the summation of them, before the submission (AJAX).

How can this be done with Drupal 7?

Thanks!


Solution

  • Yes it can be done with Ajax. The following code will automatic update the total when the text field is updated:

    function gender_total_menu()
    {
        $items = array();
    
        $items['test'] = array(
            'title'           => Gender total,
            'page callback'   => 'drupal_get_form',
            'page arguments'  => array('gender_total_form'),
            'access callback' => array(TRUE),
            'type'            => MENU_CALLBACK,
        );
    
        return $items;
    }
    
    function gender_total_form($form, &$form_state)
    {
        $total = 0;
    
        if (array_key_exists('values', $form_state) &&
            array_key_exists('field_num_males', $form_state['values']) &&
            array_key_exists('field_num_females', $form_state['values'])
        ) {
            $total = $form_state['values']['field_num_males'] + $form_state['values']['field_num_females'];
        }
    
        $form = array();
    
        $form["field_num_males"] = array(
            '#type'          => 'textfield',
            '#title'         => t("Number of males"),
            '#default_value' => 0,
            '#ajax' => array(
                'callback' => 'ajax_update_callback',
                'wrapper'  => 'wrapper',
            ),
        );
    
        $form["field_num_females"] = array(
            '#type'          => 'textfield',
            '#title'         => t("Number of females"),
            '#default_value' => 0,
            '#ajax' => array(
                'callback' => 'ajax_update_callback',
                'wrapper'  => 'wrapper',
            ),
        );
    
        $form['total'] = array(
            '#markup' => '<p> Total: ' . $total . '</p>',
            '#prefix' => '<div id="wrapper">',
            '#suffix' => '</div>',
        );
    
        return $form;
    }
    
    function ajax_update_callback($form, $form_state)
    {
        return $form['total'];
    }