0

I want to display an error message if the form field is empty.

  public function validateForm(array &$form, FormStateInterface $form_state) {
      $entry = array(
        'name' => $form_state->getValue('name'),
        'lastname' => $form_state->getValue('lastname'),
        'cardnumber' => $form_state->getValue('cardnumber'),
        'month' => $form_state->getValue('month'),
        'year' => $form_state->getValue('year'),
        'cvv' => $form_state->getValue('cvv'),    
    );
    foreach ($entry as $key => $value) {
     if (empty($value)) { 

      $form_state->setErrorByName($key, $this->t('cannot be empty.'));

        } 
     }
  }

but I only get:

cannot be empty.

If I use instead:

foreach ($entry as $key => $value) {
  if (empty($value)) { 

    drupal_set_message(t('<b>%key</b> cannot be empty.', ['%key' => $key]), 'error');

    } 
}

Results how I want it:

name cannot be empty.

lastname cannot be empty.

cardnumber cannot be empty.

month cannot be empty.

year cannot be empty.

cvv cannot be empty.

Except the problem here is that the form input box does not become highlighted in red.

How can I make it loop through the first method? or is it like that by design?

3
  • did you tried with $form_state->setErrorByName($key=>value, $this->t('cannot be empty.'));??
    – Adi
    Apr 20, 2016 at 11:25
  • 2
    Any reason why you want to do this yourself instead of using ['#required']?
    – googletorp
    Apr 20, 2016 at 12:20
  • @googletorp ugh.. I wasn't aware of that, thx. I will use this instead.
    – No Sssweat
    Apr 21, 2016 at 5:23

1 Answer 1

5

I think you simply need to replace:

$form_state->setErrorByName($key, $this->t('cannot be empty.'));

with

$form_state->setErrorByName($key, $this->t('<b>%key</b> cannot be empty.', ['%key' => $key]));

According to the docs, the first parameter will identify the field and the second will be the message to output.

In your code, the $message string is outputed as expected, you need to prefix it with the $key parameter, the same way you do with drupal_set_message.

1
  • edited your answer, as when using your original answer it filtered the <b> tags as potential harmful code and was displaying them literally on the message. Ex: <b>Name</b> cannot be empty
    – No Sssweat
    Apr 21, 2016 at 4:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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