我在一个页面上有两个drupal表单,我不明白ajax回调是如何工作的,以便根据第一个表单的值更改一个表单的值。
我的表格:
function my_form($form, &$form_state) {
$form['first_form'] = [
'#title' => t('Choose:') ,
'#type' => 'select',
'#options' => [
'1' => 'First',
'2' => 'Second',
'3' => 'Third',
],
'#required' => '1',
'#ajax' => [
'method' => 'replace',
'callback' => 'my_form_state_ajax_callback',
],
];
//---------------------
$form['second_form'] = [
'#type' => 'fieldset',
'#title' => "Second form",
];
$form['second_form']['name'] = [
'#type' => 'textfield',
'#required' => TRUE,
'#title' => 'Name.',
];
$form['second_form']['submit'] = [
'#type' => 'submit',
'#value' => "Go",
'#submit' => ['my_form_submit'],
];
}
回调函数:
function my_form_state_ajax_callback($form, &$form_state) {
switch ($form_state['values']['id']) {
case 1:
$form['second_form']['name']['#value'] = 'One';
break;
case 2:
$form['second_form']['name']['#value'] = 'Two';
break;
case 3:
$form['second_form']['name']['#value'] = 'Three';
break;
}
return $form['edit_medal'];
}
基本上,如果我在选择下拉菜单中选择First
,我想将第二个表单name
字段更改为One
等。如果我没有在选择下拉列表中选择任何内容,将不会设置第二个表单的字段的值。
上面的代码不起作用。我做错了什么?
答案 0 :(得分:1)
在此first_form中,您必须添加'wrapper'
和'prefix', 'suffix'
function my_form($form, &$form_state) {
$form['first_form'] = [
'#title' => t('Choose:') ,
'#type' => 'select',
'#options' => [
'1' => 'First',
'2' => 'Second',
'3' => 'Third',
],
'#required' => '1',
'#ajax' => [
'method' => 'replace',
'callback' => 'my_form_state_ajax_callback',
'wrapper' => 'checkboxes-div'
],
];
$form['second_form']['name'] = [
'#type' => 'textfield',
'#required' => TRUE,
'#title' => 'Name.',
'#prefix' => '<div id="checkboxes-div">',
'#suffix' => '</div>',
];
}
在回调函数中,您必须返回要更新的字段,如$form['second_form']['name']
function my_form_state_ajax_callback($form, &$form_state) {
switch ($form_state['values']['first_form']) {
case 1:
$form['second_form']['name']['#value'] = 'One';
break;
case 2:
$form['second_form']['name']['#value'] = 'Two';
break;
case 3:
$form['second_form']['name']['#value'] = 'Three';
break;
}
return $form['second_form']['name'];
}