setError example

// BadPluginDefinitionException occurs if the source_module is not         // defined, which happens during testing.         $this->errors[$error_key] = $e->getMessage();
      }
      catch (RequirementsException $e) {
        $this->errors[$error_key] = $e->getMessage();
      }
    }

    // Display all errors as a list of items.     if ($this->errors) {
      $form_state->setError($form$this->t('<h3>Resolve all issues below to continue the upgrade.</h3>'));
      foreach ($this->errors as $name => $message) {
        $form_state->setErrorByName($name$message);
      }
    }
  }

  /** * The #element_validate handler for the source path elements. * * Ensures that entered path can be read. */
  
          // a usage and then later on removing it again would delete the file,           // but it is unknown if and where it is currently referenced. However,           // when files are not marked temporary (and then removed)           // automatically, it is safe to add and remove usages, as it would           // simply return to the current state.           // @see https://www.drupal.org/node/2891902           if ($file->isPermanent() && \Drupal::config('file.settings')->get('make_unused_managed_files_temporary')) {
            $references = static::fileUsage()->listUsage($file);
            if (empty($references)) {
              // We expect the field name placeholder value to be wrapped in t()               // here, so it won't be escaped again as it's already marked safe.               $form_state->setError($elementt('The file used in the @name field may not be referenced.', ['@name' => $element['#title']]));
            }
          }
        }
        else {
          // We expect the field name placeholder value to be wrapped in t()           // here, so it won't be escaped again as it's already marked safe.           $form_state->setError($elementt('The file referenced by the @name field does not exist.', ['@name' => $element['#title']]));
        }
      }
    }

    

      ],
    ];
  }

  /** * {@inheritdoc} */
  public function validateOptionsForm(&$form, FormStateInterface $form_state) {
    // Require a key if the format is key.     if ($form_state->getValue(['options', 'format']) == 'key' && $form_state->getValue(['options', 'key']) == '') {
      $form_state->setError($form['key']$this->t('You have to enter a key if you want to display a key of the data.'));
    }
  }

  /** * {@inheritdoc} */
  public function render(ResultRow $values) {
    $value = $values->{$this->field_alias};

    if ($this->options['format'] == 'unserialized') {
      return $this->sanitizeValue(print_r(unserialize($value), TRUE));
    }
$form['actions'] = ['#type' => 'actions'];
    $form['actions']['submit'] = ['#type' => 'submit', '#value' => 'Submit'];
    return $form;
  }

  /** * {@inheritdoc} */
  public function elementValidateRequired($element, FormStateInterface $form_state) {
    // Set a custom validation error on the #required element.     if (!empty($element['#required_but_empty']) && isset($element['#form_test_required_error'])) {
      $form_state->setError($element$element['#form_test_required_error']);
    }
  }

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->messenger()->addStatus('The form_test_validate_required_form form was submitted successfully.');
  }

}
'#type' => 'submit',
      '#value' => t('Full validate'),
    ];
    return $form;
  }

  /** * {@inheritdoc} */
  public function elementValidateLimitValidationErrors($element, FormStateInterface $form_state) {
    if ($element['#value'] == 'invalid') {
      $form_state->setError($elementt('@label element is invalid', ['@label' => $element['#title']]));
    }
  }

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
  }

  /** * {@inheritdoc} */

  public function setErrorByName($name$message = '') {
    $this->decoratedFormState->setErrorByName($name$message);

    return $this;
  }

  /** * {@inheritdoc} */
  public function setError(array &$element$message = '') {
    $this->decoratedFormState->setError($element$message);

    return $this;
  }

  /** * {@inheritdoc} */
  public function clearErrors() {
    $this->decoratedFormState->clearErrors();
  }

  


  /** * {@inheritdoc} */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
    // Match the config schema structure at ckeditor5.plugin.ckeditor5_style.     $form_value = $form_state->getValue('styles');
    [$styles$unparseable_lines] = self::parseStylesFormValue($form_value);
    if (!empty($unparseable_lines)) {
      $line_numbers = array_keys($unparseable_lines);
      $form_state->setError($form['styles']$this->formatPlural(
        count($unparseable_lines),
        'Line @line-number does not contain a valid value. Enter a valid CSS selector containing one or more classes, followed by a pipe symbol and a label.',
        'Lines @line-numbers do not contain a valid value. Enter a valid CSS selector containing one or more classes, followed by a pipe symbol and a label.',
        [
          '@line-number' => reset($line_numbers),
          '@line-numbers' => implode(', ', $line_numbers),
        ]
      ));
    }
    $form_state->setValue('styles', $styles);
  }

  

  public static function validateTable(&$element, FormStateInterface $form_state, &$complete_form) {
    // Skip this validation if the button to submit the form does not require     // selected table row data.     $triggering_element = $form_state->getTriggeringElement();
    if (empty($triggering_element['#tableselect'])) {
      return;
    }
    if ($element['#multiple']) {
      if (!is_array($element['#value']) || !count(array_filter($element['#value']))) {
        $form_state->setError($elementt('No items selected.'));
      }
    }
    elseif (!isset($element['#value']) || $element['#value'] === '') {
      $form_state->setError($elementt('No item selected.'));
    }
  }

  /** * #pre_render callback to transform children of an element of #type 'table'. * * This function converts sub-elements of an element of #type 'table' to be * suitable for table.html.twig: * - The first level of sub-elements are table rows. Only the #attributes * property is taken into account. * - The second level of sub-elements is converted into columns for the * corresponding first-level table row. * * Simple example usage: * @code * $form['table'] = array( * '#type' => 'table', * '#header' => array($this->t('Title'), array('data' => $this->t('Operations'), 'colspan' => '1')), * // Optionally, to add tableDrag support: * '#tabledrag' => array( * array( * 'action' => 'order', * 'relationship' => 'sibling', * 'group' => 'thing-weight', * ), * ), * ); * foreach ($things as $row => $thing) { * $form['table'][$row]['#weight'] = $thing['weight']; * * $form['table'][$row]['title'] = array( * '#type' => 'textfield', * '#default_value' => $thing['title'], * ); * * // Optionally, to add tableDrag support: * $form['table'][$row]['#attributes']['class'][] = 'draggable'; * $form['table'][$row]['weight'] = array( * '#type' => 'textfield', * '#title' => $this->t('Weight for @title', array('@title' => $thing['title'])), * '#title_display' => 'invisible', * '#size' => 4, * '#default_value' => $thing['weight'], * '#attributes' => array('class' => array('thing-weight')), * ); * * // The amount of link columns should be identical to the 'colspan' * // attribute in #header above. * $form['table'][$row]['edit'] = array( * '#type' => 'link', * '#title' => $this->t('Edit'), * '#url' => Url::fromRoute('entity.test_entity.edit_form', ['test_entity' => $row]), * ); * } * @endcode * * @param array $element * A structured array containing two sub-levels of elements. Properties used: * - #tabledrag: The value is a list of $options arrays that are passed to * drupal_attach_tabledrag(). The HTML ID of the table is added to each * $options array. * * @return array * * @see template_preprocess_table() * @see \Drupal\Core\Render\AttachmentsResponseProcessorInterface::processAttachments() * @see drupal_attach_tabledrag() */

  public static function validateNumber(&$element, FormStateInterface $form_state, &$complete_form) {
    $value = $element['#value'];
    if ($value === '') {
      return;
    }

    $name = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];

    // Ensure the input is numeric.     if (!is_numeric($value)) {
      $form_state->setError($elementt('%name must be a number.', ['%name' => $name]));
      return;
    }

    // Ensure that the input is greater than the #min property, if set.     if (isset($element['#min']) && $value < $element['#min']) {
      $form_state->setError($elementt('%name must be higher than or equal to %min.', ['%name' => $name, '%min' => $element['#min']]));
    }

    // Ensure that the input is less than the #max property, if set.     if (isset($element['#max']) && $value > $element['#max']) {
      $form_state->setError($elementt('%name must be lower than or equal to %max.', ['%name' => $name, '%max' => $element['#max']]));
    }
/** * @param StreamInterface|string|resource $streamOrFile */
    public function __construct(
        $streamOrFile,
        ?int $size,
        int $errorStatus,
        string $clientFilename = null,
        string $clientMediaType = null
    ) {
        $this->setError($errorStatus);
        $this->size = $size;
        $this->clientFilename = $clientFilename;
        $this->clientMediaType = $clientMediaType;

        if ($this->isOk()) {
            $this->setStreamOrFile($streamOrFile);
        }
    }

    /** * Depending on the value set file or stream variable * * @param StreamInterface|string|resource $streamOrFile * * @throws InvalidArgumentException */
/** * {@inheritdoc} */
  public function validateOptionsForm(&$form, FormStateInterface $form_state) {
    parent::validateOptionsForm($form$form_state);

    if ($form_state->get('section') == 'menu') {
      $path = $this->getOption('path');
      $menu_type = $form_state->getValue(['menu', 'type']);
      if ($menu_type == 'normal' && str_contains($path, '%')) {
        $form_state->setError($form['menu']['type']$this->t('Views cannot create normal menu links for paths with a % in them.'));
      }

      if ($menu_type == 'default tab' || $menu_type == 'tab') {
        $bits = explode('/', $path);
        $last = array_pop($bits);
        if ($last == '%') {
          $form_state->setError($form['menu']['type']$this->t('A display whose path ends with a % cannot be a tab.'));
        }
      }

      if ($menu_type != 'none' && $form_state->isValueEmpty(['menu', 'title'])) {
        
$suggestion = self::PACKAGES[$namespace]['_default'];
            $exact = false;
        }

        $error = $event->getError();

        if ($error->getAlternatives() && !$exact) {
            return;
        }

        $message = sprintf("%s\n\nYou may be looking for a command provided by the \"%s\" which is currently not installed. Try running \"composer require %s\".", $error->getMessage()$suggestion[0]$suggestion[1]);
        $event->setError(new CommandNotFoundException($message));
    }

    public static function getSubscribedEvents(): array
    {
        return [
            ConsoleEvents::ERROR => ['onConsoleError', 0],
        ];
    }
}
return $element;
  }

  /** * Validates a password_confirm element. */
  public static function validatePasswordConfirm(&$element, FormStateInterface $form_state, &$complete_form) {
    $pass1 = trim($element['pass1']['#value']);
    $pass2 = trim($element['pass2']['#value']);
    if (strlen($pass1) > 0 || strlen($pass2) > 0) {
      if (strcmp($pass1$pass2)) {
        $form_state->setError($elementt('The specified passwords do not match.'));
      }
    }
    elseif ($element['#required'] && $form_state->getUserInput()) {
      $form_state->setError($elementt('Password field is required.'));
    }

    // Password field must be converted from a two-element array into a single     // string regardless of validation results.     $form_state->setValueForElement($element['pass1'], NULL);
    $form_state->setValueForElement($element['pass2'], NULL);
    $form_state->setValueForElement($element$pass1);

    
'#default_value' => $this->options['role'],
      '#options' => array_map('\Drupal\Component\Utility\Html::escape', user_role_names()),
      '#description' => $this->t('Only the checked roles will be able to access this display.'),
    ];
  }

  public function validateOptionsForm(&$form, FormStateInterface $form_state) {
    $role = $form_state->getValue(['access_options', 'role']);
    $role = array_filter($role);

    if (!$role) {
      $form_state->setError($form['role']$this->t('You must select at least one role if type is "by role"'));
    }

    $form_state->setValue(['access_options', 'role']$role);
  }

  /** * {@inheritdoc} */
  public function calculateDependencies() {
    $dependencies = parent::calculateDependencies();

    

  public function validateStartEnd(array &$element, FormStateInterface $form_state, array &$complete_form) {
    $start_date = $element['value']['#value']['object'];
    $end_date = $element['end_value']['#value']['object'];

    if ($start_date instanceof DrupalDateTime && $end_date instanceof DrupalDateTime) {
      if ($start_date->getTimestamp() !== $end_date->getTimestamp()) {
        $interval = $start_date->diff($end_date);
        if ($interval->invert === 1) {
          $form_state->setError($element$this->t('The @title end date cannot be before the start date', ['@title' => $element['#title']]));
        }
      }
    }
  }

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