Form 動態表單內容AJAX的使用

1 篇文章 / 0 new
author
Form 動態表單內容AJAX的使用
Ajax framework , 下為選擇車子廠牌後, 動態呈現該廠牌的車子型號供選擇
表單
function formexample_nameform($form, &$form_state) {    // AJAX
    $options_first = _automobile_get_manufacturer_dropdown_options();
    $selected = isset($form_state['values']['manufacturer_dropdown']) ? $form_state['values']['manufacturer_dropdown'] : key($options_first);
    $form['manufacturer_dropdown'] = array(
        '#type' => 'select',
        '#title' => 'Manufacturer',
        '#options' => $options_first,
        '#default_value' => $selected,
        // 啟用 JAAX 程序
        '#ajax' => array(
            'callback' => 'automobile_dependent_dropdown_callback',
            'wrapper' => 'dropdown_model_replace',
        ),
    );
    $form['model_dropdown'] = array(
        '#type' => 'select',
        '#title' => 'Model',
        // ajax 資料呈現的區塊
        '#prefix' => '<div id="dropdown_model_replace">',
        '#suffix' => '</div>',
        // 動態內容
        '#options' => _automobile_get_model_dropdown_options($selected),
        '#default_value' => isset($form_state['values']['model_dropdown']) ? $form_state['values']['model_dropdown'] : '',
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    return $form;
}
callback 處理
function automobile_dependent_dropdown_callback($form, $form_state) {
    return $form['model_dropdown'];//系統會重新組 $form
}
相關處理
function _automobile_get_manufacturer_dropdown_options() {
    return drupal_map_assoc(array(t('Honda'), t('Toyota'), t('Ford'), t('Volkswagen')));
}
function _automobile_get_model_dropdown_options($key = '') {
    $options = array(
        t('Honda') => drupal_map_assoc(array(t('Accord'), t('Civic'), t('CRX'), t('Pilot'))),
        t('Toyota') => drupal_map_assoc(array(t('Camry'), t('Yaris'), t('Tundra'),t('Tacoma'))),
        t('Ford') => drupal_map_assoc(array(t('F-150'), t('Explorer'), t('Escape'), t('Edge'))),
        t('Volkswagen') => drupal_map_assoc(array(t('GTI'), t('Passat'), t('Jeta'), t('Polo'))),
    );
    if (isset($options[$key])) {
        return $options[$key];
    } else {
        return array();
    }
}
Free Web Hosting