我有一个包含多个部分的表单。每个部分都有一个'#states'属性,根据上一步中选择的内容,它可以显示或隐藏。每个部分中都有一个用于添加或删除字段的按钮。单击其中一个按钮可通过AJAX调用功能。此函数使用$ form_state ['triggering_element'] ['#name']来查找单击了哪个按钮,从而将字段添加到正确的部分。问题是无论哪个部分可见,triggering_element似乎总是第一部分中的按钮。我不想把所有代码放在这里,因为它很长。以下是几个按钮的外观以及点击它调用的函数和最终回调:
$form['survey']['contents']['addsurvey'] = array(
'#type' => 'submit',
'#default_value' => t('Add Another Survey Question'),
'#submit' => array('touchpoints_metrics_add_one'),
'#limit_validation_errors' => array(),
'#name' => 'add-survey',
'#ajax' => array(
'callback' => 'touchpoints_metrics_callback',
'wrapper' => 'survey-div',
),
);
$form['mysteryshop']['contents']['addmystery'] = array(
'#type' => 'submit',
'#default_value' => t('Add Another Observation'),
'#submit' => array('touchpoints_metrics_add_one'),
'#limit_validation_errors' => array(),
'#name' => 'add-mystery',
'#ajax' => array(
'callback' => 'touchpoints_metrics_callback',
'wrapper' => 'mysteryshop-div',
),
);
function touchpoints_metrics_add_one($form, &$form_state) {
$element = $form_state['triggering_element']['#name'];
$tracker = '';
if (strpos($element, 'survey')) {
$tracker = 'num_surveys';
} elseif (strpos($element, 'mystery')) {
$tracker = 'num_mystery';
} elseif (strpos($element, 'budget')) {
$tracker = 'num_budget';
} elseif (strpos($element, 'incdec')) {
$tracker = 'num_incdec';
} elseif (strpos($element, 'roi')) {
$tracker = 'num_roi';
} elseif (strpos($element, 'epu')) {
$tracker = 'num_epu';
} elseif (strpos($element, 'response')) {
$tracker = 'num_response';
} elseif (strpos($element, 'numcomplete')) {
$tracker = 'num_numcomplete';
} elseif (strpos($element, 'perccap')) {
$tracker = 'num_perccap';
}
$form_state[$tracker]++;
$form_state['rebuild'] = TRUE;
}
function touchpoints_metrics_callback($form, &$form_state) {
$element = $form_state['triggering_element']['#name'];
$tracker = '';
if (strpos($element, 'survey')) {
$tracker = 'survey';
} elseif (strpos($element, 'mystery')) {
$tracker = 'mysteryshop';
} elseif (strpos($element, 'budget')) {
$tracker = 'budget';
} elseif (strpos($element, 'incdec')) {
$tracker = 'incdec';
} elseif (strpos($element, 'roi')) {
$tracker = 'roi';
} elseif (strpos($element, 'epu')) {
$tracker = 'epu';
} elseif (strpos($element, 'response')) {
$tracker = 'response';
} elseif (strpos($element, 'numcomplete')) {
$tracker = 'numcomplete';
} elseif (strpos($element, 'perccap')) {
$tracker = 'perccap';
}
return $form[$tracker]['contents'];
}