Drupal8:如何基于Ajax回调生成选项
在Drupal8中,我想基于对第一个选择框的Ajax调用来生成第二个选择框的选项。结果生成第三个新的选择框,但我不需要生成新的选择框。我想替换第二个选择框的选项。请参阅下面我的代码:Drupal8:如何基于Ajax回调生成选项,drupal,drupal-8,Drupal,Drupal 8,在Drupal8中,我想基于对第一个选择框的Ajax调用来生成第二个选择框的选项。结果生成第三个新的选择框,但我不需要生成新的选择框。我想替换第二个选择框的选项。请参阅下面我的代码: public function buildForm(array $form, FormStateInterface $form_state) { $form['example_select'] = [ '#type' => 'select', '#title' => $this->t('S
public function buildForm(array $form, FormStateInterface $form_state) {
$form['example_select'] = [
'#type' => 'select',
'#title' => $this->t('Select element'),
'wrapper' => 'first',
'#options' => [
'1' => $this->t('One'),
'2' => $this->t('Two'),
'3' => $this->t('Three'),
'4' => $this->t('From New York to Ger-ma-ny!'),
],
'#ajax' => [
'callback' => '::myAjaxCallback',
'disable-refocus' => FALSE,
'event' => 'change',
'wrapper' => 'edit-output',
'progress' => [
'type' => 'throbber',
'message' => $this->t('Verifying entry...'),
],
]
];
$form['example_select2'] = [
'#type' => 'select',
'#title' => $this->t('Select element'),
'#prefix' => '<div id="first">',
'#suffix' => '</div>',
'#options' => [
],
'#ajax' => [
'callback' => '::myAjaxCallback2',
'disable-refocus' => FALSE,
'event' => 'change',
'wrapper' => 'edit-output',
'progress' => [
'type' => 'throbber',
'message' => $this->t('Verifying entry...'),
],
]
];
return $form;
}
public function myAjaxCallback(array &$form, FormStateInterface $form_state) {
if ($selectedValue = $form_state->getValue('example_select')) {
$arr = array('1' => 'Nice way', '2' => 'Good way');
$form['example_select2']['#options'] = $arr;
}
return $form['example_select2'];
}
下面的代码对我来说运行良好
public function myAjaxCallback(array &$form, FormStateInterface $form_state) {
if ($selectedValue = $form_state->getValue('example_select')) {
$arr = array('1' => 'Nice way', '2' => 'Good way');
$form['example_select2']['#options'] = $arr;
}
$form_state->setRebuild(TRUE);
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand("#first", ($form['example_select2'])));
return $response;
}