變更其他模組編輯的表單項目 hook_form_alter

1 篇文章 / 0 new
author
變更其他模組編輯的表單項目 hook_form_alter
若要增加其他模組編輯的表單內容, 則需使用  hook_form_alter 來達成, 當然亦可直接修改原模組, 但若有維護更新問題時, 就不該考慮直接修改原模組的原始碼. 而是採用 hook_form_alter 方式
//Implements hook_form_alter();
function legalagree_form_alter(&$form, &$form_state, $form_id) {
// 使用者註冊或編輯資料時, $form_id 來識別當前編輯表單為何
    if (($form_id != 'user_register_form') and ($form_id != 'user_profile_form')) {
        return;
    }
// 加入新的驗證函式   
    $form['#validate'][] = 'legalagree_user_form_validate';
// add a field set
    $form['account']['legal_agreement'] = array(
        '#type' => 'fieldset',
        '#title' => t('Legal agreement')
    );
// add the radio buttons
    $form['account']['legal_agreement']['decision'] = array(
        '#type' => 'radios',
        '#description' => t('By registering at %site-name, you agree that at any time, we ....', array('%site-name' => variable_get('site_name', 'drupal'))),
        '#default_value' => 0,
        '#options' => array(t('I disagree'), t('I agree'))
    );
}
 
//驗證程序.
function legalagree_user_form_validate($form, &$form_state) {
    global $user;
    // Did user agree?   
    if ($form_state['input']['decision'] <> 1) {
        form_set_error('decision', t('You must agree to the Legal Agreement before registration can be completed.'));
    } else {
        watchdog('user', t('User %user agreed to legal terms', array('%user' => $user->name)));
    }
}
Free Web Hosting