ajax 次提交后表单输入未清除

Form input not cleared after ajax submission

我有一个包含一个字段和一个带有 ajax 提交选项的提交按钮的表单,如下所示 -

public function buildForm(array $form, FormStateInterface $form_state, $id = 0)
{       
    $form['fieldset']['message'] = array(
        '#type' => 'textfield',
        '#default_value' => "",
        '#required' => true,
        '#attributes' => array(
            'placeholder' => t('write here'),
        ),
    );

    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Send'),
        '#attributes' => array(
            'class' => array(
            ),
        ),
        '#ajax' => [
            'callback' => [$this, 'Ajaxsubmit'],
            'event' => 'click']
    );
    return $form;
}

ajax函数如下-

public function Ajaxsubmit(array $form, FormStateInterface $form_state)
    {
        $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
        $db_values = [
            "message" => $form_state->getValue("message"),
            "date_create" => date("Y-m-d H:i:s"),
        ];
        $save = DbStorage::Insert($db_values);
        //$('#mychat_form input').val("");
        //$form_state->setValue('content', NULL);

        $response = new AjaxResponse();

        if ($form_state->hasAnyErrors() || !$save) {
               $response->addCommand(new AlertCommand('something wrong!'));
        } else {

        $message = DbStorage::Get(["id" => $save]);
        $send_id = $message->send_id;
        $build = [
                '#theme' => "chat_view",
                '#message' => $message,
                '#sender' => $send_id,
                '#current_user' => true
            ];
        $ans_text = render($build);
        $response->addCommand(new AppendCommand('#mychat', $ans_text));
        }
        return $response;

    }

这里的表单数据提交工作正常。但是输入的数据在提交后并没有被清除。我尝试使用 -

从我的 javascript 中清除它
$('#my_form input').val("");  

但问题是我的 javascript 文件每 3 秒调用一次,表单输入也每 3 秒清除一次。这对用户来说是有问题的。在 ajax 提交后,还有其他方法可以清除表单输入吗?我可以在 Ajaxsubmit 函数中执行任何操作吗?

您可以使用 InvokeCommand 来完成。

例如:清除 ajax 响应中的输入值 $('#my_form input').val("");

use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\InvokeCommand;
use Drupal\Core\Ajax\AppendCommand;
:

$form['fieldset']['message'] = array(
  '#type' => 'textfield',
  '#default_value' => "",
  '#required' => true,
  '#attributes' => array(
    'placeholder' => t('write here'),
    'class' => ['custom-class'],
  ),
);

在Ajax函数中

:
$build = [
  '#theme' => "chat_view",
  '#message' => $message,
  '#sender' => $send_id,
  '#current_user' => true
];
$response->addCommand(new AppendCommand('#mychat', $build));
$response->addCommand(new InvokeCommand('.custom-class', 'val', ['']));