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?
['#required']
?