Pregunta

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!

¿Fue útil?

Solución

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'];
}

Otros consejos

Try the Computed Field module

Computed Field is a very powerful CCK field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields...

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top