addMessage example

/** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $id = $form_state->getValue('workspace_id');

    /** @var \Drupal\workspaces\WorkspaceInterface $workspace */
    $workspace = $this->workspaceStorage->load($id);

    try {
      $this->workspaceManager->setActiveWorkspace($workspace);
      $this->messenger->addMessage($this->t('%workspace_label is now the active workspace.', ['%workspace_label' => $workspace->label()]));
    }
    catch (WorkspaceAccessException $e) {
      $this->messenger->addError($this->t('You do not have access to activate the %workspace_label workspace.', ['%workspace_label' => $workspace->label()]));
    }
  }

  /** * Submit handler for switching to the live version of the site. */
  public function submitSwitchToLive(array &$form, FormStateInterface $form_state) {
    $this->workspaceManager->switchToLive();
    
public function save(array $form, FormStateInterface $form_state) {
    $workspace = $this->entity;
    $workspace->setNewRevision(TRUE);
    $status = $workspace->save();

    $info = ['%info' => $workspace->label()];
    $context = ['@type' => $workspace->bundle(), '%info' => $workspace->label()];
    $logger = $this->logger('workspaces');

    if ($status == SAVED_UPDATED) {
      $logger->notice('@type: updated %info.', $context);
      $this->messenger->addMessage($this->t('Workspace %info has been updated.', $info));
    }
    else {
      $logger->notice('@type: added %info.', $context);
      $this->messenger->addMessage($this->t('Workspace %info has been created.', $info));
    }

    if ($workspace->id()) {
      $form_state->setValue('id', $workspace->id());
      $form_state->set('id', $workspace->id());

      $collection_url = $workspace->toUrl('collection');
      

      }
    }

    if (!empty($current_user_id)) {
      $this->container->get('current_user')->setInitialAccountId($current_user_id);
    }

    // Re-add messages.     foreach ($all_messages as $type => $messages) {
      foreach ($messages as $message) {
        $this->container->get('messenger')->addMessage($message$type);
      }
    }

    \Drupal::setContainer($this->container);

    // Allow other parts of the codebase to react on container initialization in     // subrequest.     if (!empty($subrequest)) {
      $this->container->get('event_dispatcher')->dispatch(new Event(), self::CONTAINER_INITIALIZE_SUBREQUEST_FINISHED);
    }

    
->formatPlural($failures, '1 upgrade failed', '@count upgrades failed'));
      \Drupal::messenger()->addError(t('Upgrade process not completed'));
    }
    else {
      // Everything went off without a hitch. We may not have had successes       // but we didn't have failures so this is fine.       \Drupal::messenger()->addStatus(t('Congratulations, you upgraded Drupal!'));
    }

    if (\Drupal::moduleHandler()->moduleExists('dblog')) {
      $url = Url::fromRoute('migrate_drupal_ui.log');
      \Drupal::messenger()->addMessage(Link::fromTextAndUrl(new TranslatableMarkup('Review the detailed upgrade log')$url)$failures ? 'error' : 'status');
    }
  }

  /** * Reacts to item import. * * @param \Drupal\migrate\Event\MigratePostRowSaveEvent $event * The post-save event. */
  public static function onPostRowSave(MigratePostRowSaveEvent $event) {
    // We want to interrupt this batch and start a fresh one.
return [];
  }

  /** * Sets messages for testing the WebAssert methods related to messages. * * @return array * Empty array, we just need the messages. */
  public function statusMessagesForAssertions(): array {
    // Add a simple message of each type.     $this->messenger->addMessage('My Status Message', 'status');
    $this->messenger->addMessage('My Error Message', 'error');
    $this->messenger->addMessage('My Warning Message', 'warning');

    // Add messages with special characters and/or markup.     $this->messenger->addStatus('This has " in the middle');
    $this->messenger->addStatus('This has \' in the middle');
    $this->messenger->addStatus('<em>This<span>markup will be</span> escaped</em>.');
    $this->messenger->addStatus('Peaches & cream');

    return [];
  }

  

  protected function displayErrorMessages(array $form, FormStateInterface $form_state) {
    $errors = $form_state->getErrors();

    // Loop through all form errors and set an error message.     foreach ($errors as $error) {
      $this->messenger()->addMessage($error, 'error');
    }
  }

  /** * Stores errors and a list of child element errors directly on each element. * * Grouping elements like containers, details, fieldgroups and fieldsets may * need error info from their child elements to be able to accessibly show * form error messages to a user. For example, a details element should be * opened when child elements have errors. * * Grouping example: * Assume you have a 'street' element somewhere in a form, which is displayed * in a details element 'address'. It might be: * * @code * $form['street'] = [ * '#type' => 'textfield', * '#title' => $this->t('Street'), * '#group' => 'address', * '#required' => TRUE, * ]; * $form['address'] = [ * '#type' => 'details', * '#title' => $this->t('Address'), * ]; * @endcode * * When submitting an empty street field, the generated error is available to * the different render elements like so: * @code * // The street textfield element. * $element = [ * '#errors' => {Drupal\Core\StringTranslation\TranslatableMarkup}, * '#children_errors' => [], * ]; * // The address detail element. * $element = [ * '#errors' => null, * '#children_errors' => [ * 'street' => {Drupal\Core\StringTranslation\TranslatableMarkup} * ], * ]; * @endcode * * The list of child element errors of an element is an associative array. A * child element error is keyed with the #array_parents value of the * respective element. The key is formed by imploding this value with '][' as * glue. For example, a value ['contact_info', 'name'] becomes * 'contact_info][name'. * * @param array $form * An associative array containing a reference to the complete structure of * the form. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the form. * @param array $elements * An associative array containing the part of the form structure that will * be processed while traversing up the tree. For recursion only; leave * empty when calling this method. */
$actions = parent::actions($form$form_state);
    $actions['cancel']['#attributes']['class'][] = 'dialog-cancel';
    return $actions;
  }

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    try {
      $this->workspaceManager->setActiveWorkspace($this->entity);
      $this->messenger->addMessage($this->t('%workspace_label is now the active workspace.', ['%workspace_label' => $this->entity->label()]));
    }
    catch (WorkspaceAccessException $e) {
      $this->messenger->addError($this->t('You do not have access to activate the %workspace_label workspace.', ['%workspace_label' => $this->entity->label()]));
    }

    // Redirect to the workspace manage page by default.     if (!$this->getRequest()->query->has('destination')) {
      $form_state->setRedirectUrl($this->entity->toUrl());
    }
  }

  
// Mark this as an administrative page for JavaScript ("Back to site" link).     $form['#attached']['drupalSettings']['path']['currentPathIsAdmin'] = TRUE;
    return parent::buildForm($form$form_state);
  }

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->layoutTempstoreRepository->delete($this->sectionStorage);

    $this->messenger->addMessage($this->t('The changes to the layout have been discarded.'));

    $form_state->setRedirectUrl($this->getCancelUrl());
  }

}
return Url::fromRoute('entity.workspace.collection', []['query' => $this->getDestinationArray()]);
  }

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $workspace = $this->workspace;

    try {
      $workspace->publish();
      $this->messenger()->addMessage($this->t('Successful publication.'));
    }
    catch (WorkspaceAccessException $e) {
      $this->messenger()->addMessage($e->getMessage(), 'error');
    }
    catch (\Exception $e) {
      $this->messenger()->addMessage($this->t('Publication failed. All errors have been logged.'), 'error');
      $this->getLogger('workspaces')->error($e->getMessage());
    }
  }

}

  public function redirectOnSubmit(array $form, FormStateInterface $form_state) {
    $form_state->setRedirectUrl($this->sectionStorage->getLayoutBuilderUrl($form_state->getTriggeringElement()['#redirect']));
  }

  /** * {@inheritdoc} */
  public function save(array $form, FormStateInterface $form_state) {
    $return = $this->sectionStorage->save();
    $this->layoutTempstoreRepository->delete($this->sectionStorage);
    $this->messenger()->addMessage($this->t('The layout has been saved.'));
    $form_state->setRedirectUrl($this->sectionStorage->getRedirectUrl());
    return $return;
  }

  /** * Retrieves the section storage object. * * @return \Drupal\layout_builder\SectionStorageInterface * The section storage for the current form. */
  public function getSectionStorage() {
    


  /** * Finish batch. * * @param bool $success * Indicates whether the batch process was successful. * @param array $results * Results information passed from the processing callback. */
  public static function finishBatch($success$results) {
    \Drupal::messenger()->addMessage(
      \Drupal::translation()->formatPlural($results['processed'], 'One item has been processed.', '@count items have been processed.')
    );
    \Drupal::messenger()->addMessage($results['theme'] . ' theme used');
  }

}
    $form['#attached']['drupalSettings']['path']['currentPathIsAdmin'] = TRUE;
    return parent::buildForm($form$form_state);
  }

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->sectionStorage->disableLayoutBuilder()->save();
    $this->layoutTempstoreRepository->delete($this->sectionStorage);

    $this->messenger()->addMessage($this->t('Layout Builder has been disabled.'));
    $form_state->setRedirectUrl($this->getCancelUrl());
  }

}
// See if we've run the operation and need to display a report.   if ($results = $request->getSession()->remove('authorize_results')) {

    // Clear the session out.     $request->getSession()->remove('authorize_operation');
    $request->getSession()->remove('authorize_filetransfer_info');

    if (!empty($results['page_title'])) {
      $page_title = $results['page_title'];
    }
    if (!empty($results['page_message'])) {
      \Drupal::messenger()->addMessage($results['page_message']['message']$results['page_message']['type']);
    }

    $content['authorize_report'] = [
      '#theme' => 'authorize_report',
      '#messages' => $results['messages'],
    ];

    if (is_array($results['tasks'])) {
      $links = $results['tasks'];
    }
    else {
      


    $form['account']['names'] = [
      '#theme' => 'item_list',
      '#items' => $names,
    ];

    // Output a notice that user 1 cannot be canceled.     if (isset($root)) {
      $redirect = (count($accounts) == 1);
      $message = $this->t('The user account %name cannot be canceled.', ['%name' => $root->label()]);
      $this->messenger()->addMessage($message$redirect ? MessengerInterface::TYPE_ERROR : MessengerInterface::TYPE_WARNING);
      // If only user 1 was selected, redirect to the overview.       if ($redirect) {
        return $this->redirect('entity.user.collection');
      }
    }

    $form['operation'] = ['#type' => 'hidden', '#value' => 'cancel'];

    // Display account cancellation method selection, if allowed.     $user = $this->currentUser();
    $selectCancel = $user->hasPermission('administer users') || $user->hasPermission('select account cancellation method');

    

  public function getCancelUrl() {
    return new Url('<current>');
  }

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->workspaceManager->switchToLive();
    $this->messenger()->addMessage($this->t('You are now viewing the live version of the site.'));
  }

}
Home | Imprint | This part of the site doesn't use cookies.