我试图在drupal 8自定义表单中使用ajax。但它不起作用。
我是自定义表单,其中一旦用户点击复选框,文本字段就会显示一些值。这是我的代码: -
public function buildForm(array $form, FormStateInterface $form_state) {
$form['del_name'] = array(
'#type' => 'checkbox',
'#title' => $this->t('Delete users, by name'),
'#ajax' => array(
'callback' => array($this, 'my_user_callback'),
'wrapper' => 'del-name',
),
);
$form['name_placeholder'] = array(
'#type' => 'hidden',
'#prefix' => '<div id="del-name">',
'#suffix' => '</div>',
'#tree' => TRUE,
);
if (!empty($form_state->getValue('del_name')) && $form_state->getValue('del_name')) {
/*
* $process_data = some stuff
*/
$form['name_placeholder']['user_role'] = array(
'#title' => $this->t('Users role'),
'#type' => 'textfield',
'#default_value' => $process_data
);
}
}
function my_user_callback(array &$form, FormStateInterface $form_state) {
return array(
'#type' => 'ajax',
'#commands' => array(
ajax_command_replace('#del-name', render($form['name_placeholder'])),
)
);
}
问题是,选中复选框后,文本字段不会出现。
答案 0 :(得分:1)
试试这个:
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
function my_user_callback(array &$form, FormStateInterface $form_state {
$response = new AjaxResponse();
$response->addCommand(new HtmlCommand(
'#wrapper-element-id',
$array_of_form_elements
));
return $response;
);