You are here

class ModalForm in Editor Notes 8

Implements the ModalForm form controller.

This example demonstrates implementation of a form that is designed to be used as a modal form. To properly display the modal the link presented by the \Drupal\form_api_example\Controller\Page page controller loads the Drupal dialog and ajax libraries. The submit handler in this class returns ajax commands to replace text in the calling page after submission .

Hierarchy

Expanded class hierarchy of ModalForm

See also

\Drupal\Core\Form\FormBase

1 string reference to 'ModalForm'
editor_note.routing.yml in ./editor_note.routing.yml
editor_note.routing.yml

File

src/Form/ModalForm.php, line 29

Namespace

Drupal\editor_note\Form
View source
class ModalForm extends FormBase {

  /**
   * The messenger.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * The editor note helper.
   *
   * @var \Drupal\editor_note\EditorNoteHelperService
   */
  protected $editorNoteHelper;

  /**
   * Form constructor.
   *
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger.
   * @param \Drupal\editor_note\EditorNoteHelperService $editorNoteHelper
   *   Editor note helpers.
   */
  public function __construct(MessengerInterface $messenger, EditorNoteHelperService $editorNoteHelper) {
    $this->messenger = $messenger;
    $this->editorNoteHelper = $editorNoteHelper;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('messenger'), $container
      ->get('editor_note.helper'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'modal_form';
  }

  /**
   * Helper method so we can have consistent dialog options.
   *
   * @return string[]
   *   An array of jQuery UI elements to pass on to our dialog form.
   */
  protected static function getDataDialogOptions() {
    return [
      'width' => '50%',
    ];
  }

  /**
   * Returns current EditorNote entity.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state object.
   *
   * @return \Drupal\editor_note\Entity\EditorNote|null
   *   Editor note entity.
   */
  protected function getEditorNoteEntity(FormStateInterface $form_state) {
    $editor_note = NULL;
    $build_info = $form_state
      ->getBuildInfo();
    if (!empty($build_info['args'][0])) {
      if ($build_info['args'][0] instanceof EditorNote) {
        $editor_note = $build_info['args'][0];
      }
    }
    return $editor_note;
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, EditorNote $editor_note = NULL, $nojs = NULL) {

    // Add the core AJAX library.
    $form['#attached']['library'][] = 'core/drupal.ajax';

    // Add a link to show this form in a modal dialog if we're not already in
    // one.
    if ($nojs == 'nojs') {
      $form['use_ajax_container'] = [
        '#type' => 'details',
        '#open' => TRUE,
      ];
      $form['use_ajax_container']['description'] = [
        '#type' => 'item',
        '#markup' => $this
          ->t('In order to show a modal dialog by clicking on a link, that link has to have class <code>use-ajax</code> and <code>data-dialog-type="modal"</code>. This link has those attributes.'),
      ];
      $form['use_ajax_container']['use_ajax'] = [
        '#type' => 'link',
        '#title' => $this
          ->t('Edit in modal.'),
        '#url' => Url::fromRoute('editor_note.modal_form', [
          'editor_note' => $editor_note
            ->id(),
          'nojs' => 'ajax',
        ]),
        '#attributes' => [
          'class' => [
            'use-ajax',
          ],
          'data-dialog-type' => 'modal',
          'data-dialog-options' => json_encode(static::getDataDialogOptions()),
          // Add this id so that we can test this form.
          'id' => 'ajax-example-modal-link',
        ],
      ];
      $form['use_ajax_container']['delete'] = [
        '#type' => 'link',
        '#title' => $this
          ->t('Delete in modal.'),
        '#url' => Url::fromRoute('editor_note.confirm_delete_editor_note_form', [
          'nojs' => 'ajax',
        ]),
        '#attributes' => [
          'class' => [
            'use-ajax',
          ],
          'data-dialog-type' => 'modal',
          'data-dialog-options' => json_encode(static::getDataDialogOptions()),
          // Add this id so that we can test this form.
          'id' => 'ajax-example-modal-link',
        ],
      ];
    }

    // This element is responsible for displaying form errors in the AJAX
    // dialog.
    if ($nojs == 'ajax') {
      $form['status_messages'] = [
        '#type' => 'status_messages',
        '#weight' => -999,
      ];
    }
    $note_value = $editor_note->note->value;
    $user_input = $form_state
      ->getUserInput();
    if (!empty($user_input['editor_note'])) {
      $note_input = $user_input['editor_note'];
      if (isset($note_input['value'])) {
        $note_value = $note_input['value'];
      }
    }
    $form['editor_note'] = [
      '#type' => 'textarea',
      '#default_value' => $note_value,
      '#required' => TRUE,
      '#title' => $this
        ->t('Update note'),
      '#weight' => '0',
    ];

    // Group submit handlers in an actions element with a key of "actions" so
    // that it gets styled correctly, and so that other modules may add actions
    // to the form.
    $form['actions'] = [
      '#type' => 'actions',
    ];

    // Add a submit button that handles the submission of the form.
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Update'),
      '#ajax' => [
        'callback' => '::ajaxSubmitForm',
        'event' => 'click',
      ],
    ];

    // Set the form to not use AJAX if we're on a nojs path. When this form is
    // within the modal dialog, Drupal will make sure we're using an AJAX path
    // instead of a nojs one.
    if ($nojs == 'nojs') {
      unset($form['actions']['submit']['#ajax']);
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $input = $form_state
      ->getValue('editor_note');
    if (empty($input)) {
      $form_state
        ->setError($form['editor_note'], $this
        ->t('Note text is empty.'));
    }
  }

  /**
   * Updates EditorNote entity.
   *
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $title = $form_state
      ->getValue('title');
    if ($editor_note = $this
      ->getEditorNoteEntity($form_state)) {
      $note = $form_state
        ->getValue('editor_note');
      $new_note = [
        'value' => Xss::filterAdmin($note),
        // @todo: implement support for text formats.
        'format' => 'plain_text',
      ];
      $editor_note
        ->set('note', $new_note);
      $editor_note
        ->save();
    }
    $this->messenger
      ->addMessage($this
      ->t('Submit handler: You specified a title of @title.', [
      '@title' => $title,
    ]));
  }

  /**
   * Implements the submit handler for the modal dialog AJAX call.
   *
   * @param array $form
   *   Render array representing from.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Current form state.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   Array of AJAX commands to execute on submit of the modal form.
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function ajaxSubmitForm(array &$form, FormStateInterface $form_state) {

    // We begin building a new ajax reponse.
    $response = new AjaxResponse();

    // If the user submitted the form and there are errors, show them the
    // input dialog again with error messages. Since the title element is
    // required, the empty string wont't validate and there will be an error.
    if ($form_state
      ->getErrors()) {

      // If there are errors, we can show the form again with the errors in
      // the status_messages section.
      $form['status_messages'] = [
        '#type' => 'status_messages',
        '#weight' => -10,
      ];
      $response
        ->addCommand(new OpenModalDialogCommand($this
        ->t('Errors'), $form, static::getDataDialogOptions()));
    }
    else {

      // We don't want any messages that were added by submitForm().
      $this->messenger
        ->deleteAll();
      $editor_note = $this
        ->getEditorNoteEntity($form_state);

      // This will be the contents for the modal dialog.
      $content = [
        '#type' => 'item',
        '#markup' => $this
          ->t('Note has been updated and saved.'),
      ];

      // Add the OpenModalDialogCommand to the response. This will cause Drupal
      // AJAX to show the modal dialog. The user can click the little X to close
      // the dialog.
      $response
        ->addCommand(new OpenModalDialogCommand($this
        ->t('Update selected item'), $content, static::getDataDialogOptions()));

      // Refresh editor note table.
      $replace_command = $this->editorNoteHelper
        ->getWidgetAjaxReplaceCommand($editor_note);
      $response
        ->addCommand($replace_command);
    }

    // Finally return our response.
    return $response;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
ModalForm::$editorNoteHelper protected property The editor note helper.
ModalForm::$messenger protected property The messenger. Overrides MessengerTrait::$messenger
ModalForm::ajaxSubmitForm public function Implements the submit handler for the modal dialog AJAX call.
ModalForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
ModalForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ModalForm::getDataDialogOptions protected static function Helper method so we can have consistent dialog options.
ModalForm::getEditorNoteEntity protected function Returns current EditorNote entity.
ModalForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ModalForm::submitForm public function Updates EditorNote entity. Overrides FormInterface::submitForm
ModalForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
ModalForm::__construct public function Form constructor.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.