What is the good way of validating a form in Drupal 8 ?

I have a bunch of fields which are supposed to be filled by a positive numeric value (and that's all, no other input types, just positive int).

public function validateForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();

foreach ($values as $method => $fee) {
  if ($method != 'Free order') {
    if (!is_numeric($fee) || floatval($fee) < 0) {
      $form_state->setErrorByName($method, t('Value must be a positive integer.'));
    }
  }
}

}

The issue is when using $form_state->getValues() it also returns "submit", "form_token", "form_build", "form_id", "op" which is quite boring as those infos are not needed for performing validation.

So what I did is removing those four unwanted values with :

$values = array_splice($values, count($values) - 5, 5);

But it's really annoying, am I doing something wrong, or is just as it ? Because I think those values are really not necessary in the validation process.

  • 2
    The answer is correct, but there are two other alternatives that you might want to consider. a) If this is really everything you need, then just use #type number and #min => 0. That will cover that validation automatically, it will also do it already in the browser and e.g. mobile clients will automatically show a number-only keyboard. Everyone wins. b) Or, consider putting your elements inside a common key, just do something like $form['numbers']['#tree'] = TRUE, put them below that in the array and then $form_state->getValue('numbers') and you just get your elements, no cleaning necessary. – Berdir Oct 15 at 18:21
  • I was struggling a bit about how to get floated values with the 'number' field type. You actually have to put a '#step' of 0.01 for example if you want 2 decimal after the integer. – Aporie Oct 25 at 8:54
up vote 8 down vote accepted

The FormState class has a method for that: FormState::cleanValues(). From its description, it's the method you should use.

This function can be used when a module wants to store all submitted form values, for example, by serializing them into a single database column. In such cases, all internal Form API values and all form button elements should not be contained, and this function allows their removal before the module proceeds to storage. Next to button elements, the following internal values are removed by default.

  • form_id
  • form_token
  • form_build_id
  • op

You simply call it before getting the submitted values.

public function validateForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state->cleanValues()->getValues();

  foreach ($values as $method => $fee) {
    if ($method != 'Free order') {
      if (!is_numeric($fee) || floatval($fee) < 0) {
        $form_state->setErrorByName($method, t('Value must be a positive integer.'));
      }
    }
  }

Since FormState::cleanValues() returns the FormState object, you can simply call it in the same line you call FormState::getValues() concatenating the two calls.

If you need to add more keys to remove from the submitted values, you could use FormState::setCleanValueKeys(), but keep in mind that:

  • The array passed to the method needs to contain also the default array keys Drupal would remove
  • The method alters the array keys that are removed from FormState::cleanValues() for every Drupal form

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.