Drupal → AJAX команда для сброса значений полей формы

12.01.2021
// src/Ajax/FormResetCommand.php

namespace Drupal\modulename\Ajax;

use Drupal\Core\Ajax\CommandInterface;

class FormResetCommand implements CommandInterface {

  protected string $form_selector;

  public function __construct(string $form_selector) {
    $this->form_selector = $form_selector;
  }

  public function render(): array {
    return [
      'command' => 'invoke',
      'selector' => $this->form_selector,
      'method' => 'trigger',
      'args' => ['reset'],
    ];
  }

}

Использование:

$response = new AjaxResponse();
$response->addCommand(new FormResetCommand('#my-form-id'));
return $response;

Кейс — после сабмита показываем пользователю сообщение в диалоге и сбрасываем форму, чтобы не было желания ещё раз её отправить.

Написанное актуально для
Drupal 8+
Похожие записи

Добавить комментарий