我已經在drupal 7中解決了這個問題。首先我按照要求使用Ajax解決它(如果有人想我可以将它轉換為drupal6),但是使用屬性#states來解決這個問題應該更好。是以也使用狀态在底部做了一個解決方案。
如何使用Ajax解決這個問題:
function ajax_in_drupal_form($form, &$form_state)
{
$baseball = array(
'like' => t('I like Baseball'),
'unlike' => t('I don't like Baseball')
);
$form['step'] = array(
'#prefix' => '
',
'#suffix' => '
',
);
if ($form_state['values']['baseball'] == 'like') {
$form['step']['team'] = array(
'#type' => 'textfield',
'#title' => t('My favorite team is'),
);
$form['step']['player'] = array(
'#type' => 'textfield',
'#title' => t('The player I like most is'),
);
}
else if ($form_state['values']['baseball'] == 'unlike') {
$form['step']['other'] = array(
'#type' => 'textfield',
'#title' => t('What do you like'),
);
}
else {
$form['step']['baseball'] = array(
'#type' => 'radios',
'#options' => $baseball,
'#title' => t('Select your option'),
'#ajax' => array(
'callback' => 'ajax_update_step_callback',
'wrapper' => 'baseball-wrapper',
),
);
}
return $form;
}
function ajax_update_step_callback($form, $form_state) {
return $form['step'];
}
這是使用#states的解決方案(解決它的首選方法):
function states_in_drupal_form($form, &$form_state)
{
$baseball = array(
'like' => t('I like Baseball'),
'unlike' => t('I don't like Baseball')
);
// step 1
$form['step']['baseball'] = array(
'#type' => 'radios',
'#options' => $baseball,
'#title' => t('Select your option'),
'#states' => array(
'invisible' => array(':input[name="baseball"]' => array('checked' => TRUE),
),
)
);
// step 2 like baseball
$form['step']['team'] = array(
'#type' => 'textfield',
'#title' => t('My favorite team is'),
'#states' => array(
'visible' => array(':input[name="baseball"]' => array('checked' => TRUE)),
'visible' => array(':input[name="baseball"]' => array('value' => 'like')),
)
);
$form['step']['player'] = array(
'#type' => 'textfield',
'#title' => t('The player I like most is'),
'#states' => array(
'visible' => array(':input[name="baseball"]' => array('checked' => TRUE)),
'visible' => array(':input[name="baseball"]' => array('value' => 'like')),
)
);
// step 2 I don't like baseball
$form['step']['other'] = array(
'#type' => 'textfield',
'#title' => t('What do you like'),
'#states' => array(
'visible' => array(':input[name="baseball"]' => array('checked' => TRUE)),
'visible' => array(':input[name="baseball"]' => array('value' => 'unlike')),
)
);
return $form;
}