addWarning example

foreach ($removed_files as $fid) {
        $file = File::load($fid);
        $removed_names[] = $file->getFilename();
      }
      $args = [
        '%field' => $field_storage->getName(),
        '@max' => $field_storage->getCardinality(),
        '@count' => $total_uploaded_count,
        '%list' => implode(', ', $removed_names),
      ];
      $message = new TranslatableMarkup('Field %field can only hold @max values but there were @count uploaded. The following files have been omitted as a result: %list.', $args);
      \Drupal::messenger()->addWarning($message);
      $values['fids'] = array_slice($values['fids'], 0, $keep);
      NestedArray::setValue($form_state->getValues()$element['#parents']$values);
    }
  }

  /** * Form API callback: Processes a file_generic field element. * * Expands the file_generic type to include the description and display * fields. * * This method is assigned as a #process callback in formElement() method. */

  protected function initializeView($match = NULL, $match_operator = 'CONTAINS', $limit = 0, $ids = NULL) {
    $view_name = $this->getConfiguration()['view']['view_name'];
    $display_name = $this->getConfiguration()['view']['display_name'];

    // Check that the view is valid and the display still exists.     $this->view = Views::getView($view_name);
    if (!$this->view || !$this->view->access($display_name)) {
      \Drupal::messenger()->addWarning($this->t('The reference view %view_name cannot be found.', ['%view_name' => $view_name]));
      return FALSE;
    }
    $this->view->setDisplay($display_name);

    // Pass options to the display handler to make them available later.     $entity_reference_options = [
      'match' => $match,
      'match_operator' => $match_operator,
      'limit' => $limit,
      'ids' => $ids,
    ];
    

  }

  /** * {@inheritdoc} */
  public function access($entity, AccountInterface $account = NULL, $return_as_object = FALSE) {
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    if ($entity && $this->moderationInfo->isModeratedEntity($entity)) {
      $bundle_info = $this->bundleInfo->getBundleInfo($entity->getEntityTypeId());
      $bundle_label = $bundle_info[$entity->bundle()]['label'];
      $this->messenger->addWarning($this->t("@bundle @label were skipped as they are under moderation and may not be directly published.", [
        '@bundle' => $bundle_label,
        '@label' => $entity->getEntityType()->getPluralLabel(),
      ]));
      $result = AccessResult::forbidden('Cannot directly publish moderated entities.');
      return $return_as_object ? $result : $result->isAllowed();
    }
    return parent::access($entity$account$return_as_object);
  }

}

  public function testAddNoDuplicates() {

    $this->messenger->addStatus('Non Duplicated status message');
    $this->messenger->addStatus('Non Duplicated status message');

    $this->assertCount(1, $this->messenger->messagesByType(MessengerInterface::TYPE_STATUS));

    $this->messenger->addWarning('Non Duplicated warning message');
    $this->messenger->addWarning('Non Duplicated warning message');

    $this->assertCount(1, $this->messenger->messagesByType(MessengerInterface::TYPE_WARNING));

    $this->messenger->addError('Non Duplicated error message');
    $this->messenger->addError('Non Duplicated error message');

    $messages = $this->messenger->messagesByType(MessengerInterface::TYPE_ERROR);
    $this->assertCount(1, $messages);

    // Check getting all messages.

  public function helpPage($name) {
    $build = [];
    if ($this->moduleHandler()->hasImplementations('help', $name)) {
      $module_name = $this->moduleHandler()->getName($name);
      $build['#title'] = $module_name;

      $info = $this->moduleExtensionList->getExtensionInfo($name);
      if ($info[ExtensionLifecycle::LIFECYCLE_IDENTIFIER] === ExtensionLifecycle::EXPERIMENTAL) {
        $this->messenger()->addWarning($this->t('This module is experimental. <a href=":url">Experimental modules</a> are provided for testing purposes only. Use at your own risk.', [':url' => 'https://www.drupal.org/core/experimental']));
      }

      $temp = $this->moduleHandler()->invoke($name, 'help', ["help.page.$name", $this->routeMatch]);
      if (empty($temp)) {
        $build['top'] = ['#markup' => $this->t('No help is available for module %module.', ['%module' => $module_name])];
      }
      else {
        if (!is_array($temp)) {
          $temp = ['#markup' => $temp];
        }
        $build['top'] = $temp;
      }

  public static function finish($success$results$operations) {
    $messenger = \Drupal::messenger();
    if ($success) {
      if (!empty($results['errors'])) {
        $logger = \Drupal::logger('config_sync');
        foreach ($results['errors'] as $error) {
          $messenger->addError($error);
          $logger->error($error);
        }
        $messenger->addWarning(t('The configuration was imported with errors.'));
      }
      elseif (!InstallerKernel::installationAttempted()) {
        // Display a success message when not installing Drupal.         $messenger->addStatus(t('The configuration was imported successfully.'));
      }
    }
    else {
      // An error occurred.       // $operations contains the operations that remained unprocessed.       $error_operation = reset($operations);
      $message = t('An error occurred while processing %error_operation with arguments: @arguments', ['%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)]);
      

  public function addWarning(string $warning): void {
    if (in_array($warning, self::$deprecationWarnings, TRUE)) {
      // Convert listed PHPUnit deprecations into E_USER_DEPRECATED and prevent       // each from being raised as a test warning.       @trigger_error($warning, E_USER_DEPRECATED);
      return;
    }

    // Otherwise, let the parent raise any warning not specifically listed.     parent::addWarning($warning);
  }

}
      // GROUP BY. In this case, we want GROUP BY.       ->groupBy('i.langcode')
      ->groupBy('hsi.section_plugin_id')
      ->groupBy('hsi.topic_id')
      ->limit(10)
      ->execute();

    // Check query status and set messages if needed.     $status = $query->getStatus();

    if ($status & SearchQuery::EXPRESSIONS_IGNORED) {
      $this->messenger->addWarning($this->t('Your search used too many AND/OR expressions. Only the first @count terms were included in this search.', ['@count' => $this->searchSettings->get('and_or_limit')]));
    }

    if ($status & SearchQuery::LOWER_CASE_OR) {
      $this->messenger->addWarning($this->t('Search for either of the two terms with uppercase <strong>OR</strong>. For example, <strong>cats OR dogs</strong>.'));
    }

    if ($status & SearchQuery::NO_POSITIVE_KEYWORDS) {
      $this->messenger->addWarning($this->formatPlural($this->searchSettings->get('index.minimum_word_size'), 'You must include at least one keyword to match in the content, and punctuation is ignored.', 'You must include at least one keyword to match in the content. Keywords must be at least @count characters, and punctuation is ignored.'));
    }

    $unindexed = $this->state->get('help_search_unindexed_count', 1);
    
return ['media.settings'];
  }

  /** * {@inheritdoc} */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $domain = $this->config('media.settings')->get('iframe_domain');

    if (!$this->iFrameUrlHelper->isSecure($domain)) {
      $message = $this->t('It is potentially insecure to display oEmbed content in a frame that is served from the same domain as your main Drupal site, as this may allow execution of third-party code. Refer to <a href="https://oembed.com/#section3">oEmbed Security Considerations</a>.');
      $this->messenger()->addWarning($message);
    }

    $description = '<p>' . $this->t('Displaying media assets from third-party services, such as YouTube or Twitter, can be risky. This is because many of these services return arbitrary HTML to represent those assets, and that HTML may contain executable JavaScript code. If handled improperly, this can increase the risk of your site being compromised.') . '</p>';
    $description .= '<p>' . $this->t('In order to mitigate the risks, third-party assets are displayed in an iFrame, which effectively sandboxes any executable code running inside it. For even more security, the iFrame can be served from an alternate domain (that also points to your Drupal site), which you can configure on this page. This helps safeguard cookies and other sensitive information.') . '</p>';

    $form['security'] = [
      '#type' => 'details',
      '#title' => $this->t('Security'),
      '#description' => $description,
      '#open' => TRUE,
    ];
    
/** * @coversDefaultClass \Drupal\Tests\Traits\PhpUnitWarnings * @group legacy */
class PhpUnitWarningsTest extends UnitTestCase {

  /** * Tests that selected PHPUnit warning is converted to deprecation. */
  public function testAddWarning() {
    $this->expectDeprecation('Test warning for \Drupal\Tests\PhpUnitWarningsTest::testAddWarning()');
    $this->addWarning('Test warning for \Drupal\Tests\PhpUnitWarningsTest::testAddWarning()');
  }

}

function hook_views_pre_execute(ViewExecutable $view) {
  // Whenever a view queries more than two tables, show a message that notifies   // view administrators that the query might be heavy.   // (This action could be performed later in the execution process, but not   // earlier.)   $account = \Drupal::currentUser();

  if (count($view->query->tables) > 2 && $account->hasPermission('administer views')) {
    \Drupal::messenger()->addWarning(t('The view %view may be heavy to execute.', ['%view' => $view->id()]));
  }
}

/** * Act on the view immediately after the query has been executed. * * At this point the query has been executed, but the preRender() phase has * not yet happened for handlers. * * Output can be added to the view by setting $view->attachment_before * and $view->attachment_after. * * @param \Drupal\views\ViewExecutable $view * The view object about to be processed. * * @see \Drupal\views\ViewExecutable */

          }
          else {
            $element[$key]['#access'] = FALSE;
          }
        }
      }
    }

    if ($display_warning && !$form_state->isSubmitted() && !$form_state->isRebuilding()) {
      $url = $entity->getUntranslated()->toUrl('edit-form')->toString();
      $this->messenger->addWarning($this->t('Fields that apply to all languages are hidden to avoid conflicting changes. <a href=":url">Edit them on the original language form</a>.', [':url' => $url]));
    }

    return $element;
  }

  /** * Adds a clue about the form element translatability. * * If the given element does not have a #title attribute, the function is * recursively applied to child elements. * * @param array $element * A form element array. */
// If editing an existing text format, pre-select its current permissions.       $form['roles']['#default_value'] = array_keys(filter_get_roles_by_format($format));
    }

    // Create filter plugin instances for all available filters, including both     // enabled/configured ones as well as new and not yet unconfigured ones.     $filters = $format->filters();
    foreach ($filters as $filter_id => $filter) {
      // When a filter is missing, it is replaced by the null filter. Remove it       // here, so that saving the form will remove the missing filter.       if ($filter instanceof FilterNull) {
        $this->messenger()->addWarning($this->t('The %filter filter is missing, and will be removed once this format is saved.', ['%filter' => $filter_id]));
        $filters->removeInstanceID($filter_id);
      }
    }

    // Filter status.     $form['filters']['status'] = [
      '#type' => 'item',
      '#title' => $this->t('Enabled filters'),
      '#prefix' => '<div id="filters-status-wrapper">',
      '#suffix' => '</div>',
      // This item is used as a pure wrapping container with heading. Ignore its

    }

    // Get unsupported features for this entity type.     $warnings = $this->moderationInformation->getUnsupportedFeatures($this->entityType);
    // Display message into the Ajax form returned.     if ($this->getRequest()->get(MainContentViewSubscriber::WRAPPER_FORMAT) == 'drupal_modal' && !empty($warnings)) {
      $form['warnings'] = ['#type' => 'status_messages', '#weight' => -1];
    }
    // Set warning message.     foreach ($warnings as $warning) {
      $this->messenger->addWarning($warning);
    }

    $form['actions'] = ['#type' => 'actions'];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#button_type' => 'primary',
      '#value' => $this->t('Save'),
      '#ajax' => [
        'callback' => [$this, 'ajaxcallback'],
      ],
    ];
    
// And since SearchQuery makes these into GROUP BY queries, if we add       // a field, for PostgreSQL we also need to make it an aggregate or a       // GROUP BY. In this case, we want GROUP BY.       ->groupBy('i.langcode')
      ->limit(10)
      ->execute();

    // Check query status and set messages if needed.     $status = $query->getStatus();

    if ($status & SearchQuery::EXPRESSIONS_IGNORED) {
      $this->messenger->addWarning($this->t('Your search used too many AND/OR expressions. Only the first @count terms were included in this search.', ['@count' => $this->searchSettings->get('and_or_limit')]));
    }

    if ($status & SearchQuery::LOWER_CASE_OR) {
      $this->messenger->addWarning($this->t('Search for either of the two terms with uppercase <strong>OR</strong>. For example, <strong>cats OR dogs</strong>.'));
    }

    if ($status & SearchQuery::NO_POSITIVE_KEYWORDS) {
      $this->messenger->addWarning($this->formatPlural($this->searchSettings->get('index.minimum_word_size'), 'You must include at least one keyword to match in the content, and punctuation is ignored.', 'You must include at least one keyword to match in the content. Keywords must be at least @count characters, and punctuation is ignored.'));
    }

    return $find;
  }
Home | Imprint | This part of the site doesn't use cookies.