【问题标题】:Ajax not working in drupal 8 custom formAjax 不能在 drupal 8 自定义表单中工作
【发布时间】:2016-02-09 10:07:48
【问题描述】:

我正在尝试在 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'])),
        )
      );
  }

问题是,选中复选框时不会出现文本字段。

【问题讨论】:

  • 有什么问题?
  • 有人有什么建议吗?

标签: drupal drupal-8


【解决方案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;
);

【讨论】:

  • 感谢@Nothing,它的工作只需稍作改动。我删除了 '#type' => 'hidden',这个语句也删除了。
猜你喜欢
  • 1970-01-01
  • 2020-02-24
  • 2016-10-03
  • 2017-10-10
  • 2020-06-21
  • 2015-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多