You are here

class AnnounceCommand in Drupal 10

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Ajax/AnnounceCommand.php \Drupal\Core\Ajax\AnnounceCommand
  2. 9 core/lib/Drupal/Core/Ajax/AnnounceCommand.php \Drupal\Core\Ajax\AnnounceCommand

AJAX command for a JavaScript Drupal.announce() call.

Developers should be extra careful if this command and \Drupal\Core\Ajax\MessageCommand are included in the same response. By default, MessageCommand will also call Drupal.announce() and announce the message to the screen reader (unless the option to suppress announcements is passed to the constructor). Manual testing with a screen reader is strongly recommended.

Hierarchy

  • class \Drupal\Core\Ajax\AnnounceCommand implements \Drupal\Core\Ajax\CommandInterface, \Drupal\Core\Ajax\CommandWithAttachedAssetsInterface

Expanded class hierarchy of AnnounceCommand

See also

\Drupal\Core\Ajax\MessageCommand

Related topics

3 files declare their use of AnnounceCommand
AjaxCommandsTest.php in core/tests/Drupal/Tests/Core/Ajax/AjaxCommandsTest.php
ajax_forms_test.module in core/modules/system/tests/modules/ajax_forms_test/ajax_forms_test.module
Mock module for Ajax forms testing.
MediaLibraryWidget.php in core/modules/media_library/src/Plugin/Field/FieldWidget/MediaLibraryWidget.php

File

core/lib/Drupal/Core/Ajax/AnnounceCommand.php, line 21

Namespace

Drupal\Core\Ajax
View source
class AnnounceCommand implements CommandInterface, CommandWithAttachedAssetsInterface {

  /**
   * The assertive priority attribute value.
   *
   * @var string
   */
  const PRIORITY_ASSERTIVE = 'assertive';

  /**
   * The polite priority attribute value.
   *
   * @var string
   */
  const PRIORITY_POLITE = 'polite';

  /**
   * The text to be announced.
   *
   * @var string
   */
  protected $text;

  /**
   * The priority that will be used for the announcement.
   *
   * @var string
   */
  protected $priority;

  /**
   * Constructs an AnnounceCommand object.
   *
   * @param string $text
   *   The text to be announced.
   * @param string|null $priority
   *   (optional) The priority that will be used for the announcement. Defaults
   *   to NULL which will not set a 'priority' in the response sent to the
   *   client and therefore the JavaScript Drupal.announce() default of 'polite'
   *   will be used for the message.
   */
  public function __construct($text, $priority = NULL) {
    $this->text = $text;
    $this->priority = $priority;
  }

  /**
   * {@inheritdoc}
   */
  public function render() {
    $render = [
      'command' => 'announce',
      'text' => $this->text,
    ];
    if ($this->priority !== NULL) {
      $render['priority'] = $this->priority;
    }
    return $render;
  }

  /**
   * {@inheritdoc}
   */
  public function getAttachedAssets() {
    $assets = new AttachedAssets();
    $assets
      ->setLibraries([
      'core/drupal.announce',
    ]);
    return $assets;
  }

}

Members