문제

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!

도움이 되었습니까?

해결책

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

다른 팁

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...

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top