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?


1 Answer 1


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(),

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.