Score:3

How to get the field name in a validation handler?

kz flag

I have a custom class TextWidget extends WidgetBase

Inside it I have a custom validation handler that looks like this:

public function validate($element, FormStateInterface $form_state) {
  $value = $element['#value'];
  $label = 'This field'; // What method is there to get the human facing field name?
  if (strlen($value) === 0) {
    $form_state->setError($element, $this->t('@label cannot be empty.', ['@label' => $label]));
  }
}

It outputs the error "This field cannot be empty." if the field is empty.

I want to replace the static text 'This field' with the actual human facing name of the field.

Is there a public method that lets me do that?

Score:7
us flag

A class that extends WidgetBase can get the label with $this->fieldDefinition->getLabel(). That is used, for example, from WidgetBase::form().

$element = [
  '#title' => $this->fieldDefinition->getLabel(),
  '#description' => $this->getFilteredDescription(),
];
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.