【问题标题】:Drupal 7, how to dynamically populate a field based on the summation of two other fields?Drupal 7,如何根据其他两个字段的总和动态填充一个字段?
【发布时间】:2012-02-25 13:56:23
【问题描述】:

我有两个字段

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

我需要在提交 (AJAX) 之前用它们的总和动态填充字段 $form["field_gender_total"]。

如何使用 Drupal 7 做到这一点?

谢谢!

【问题讨论】:

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


    【解决方案1】:

    是的,它可以通过 Ajax 完成。以下代码会在更新文本字段时自动更新总数:

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

    【讨论】:

      【解决方案2】:

      试试Computed Field 模块

      Computed Field 是一个非常强大的 CCK 字段模块,可让您添加 自定义“计算字段”到您的内容类型。这些计算域 填充有您通过 PHP 代码定义的值。你可以画 Drupal 可用的任何内容,包括其他字段...

      【讨论】:

      • 填写表格时是否会即时填充字段?我认为计算字段是隐藏的,并保存在数据库中....
      猜你喜欢
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      • 1970-01-01
      • 2021-08-09
      • 2010-10-06
      相关资源
      最近更新 更多