I'd like to use a hook to modify a widget, but only for a named field.

Use case: a form has an entity reference to another content type, using an options_buttons widget (a list of available courses the user can apply for). Rather than just the title alongside each checkbox, I'd like to display some extra fields from the content type such as date, a URL etc.

The documentation suggests $context['widget'] ("The widget plugin instance.") is the place to look, however a var_dump of that just seems to give me lots of protected properties and no clear way of getting the field name.

Essentially I'm after a D8 version similar to this old example I found:

if ($context['field']['field_name'] != 'field_bannerimage') return;
  • 1
    I suggest you use kint($context['widget']); and see what are the available methods. I go in detail on how to do that here, see the "Getting a value" section.
    – No Sssweat
    Jun 3, 2018 at 21:08
  • 1
    @NoSssweat - I'd tried kint() earlier and had given up because the output was blank. Have now realised that was because I was testing as an anonymous user and hadn't set the "Access kint information" permission… Jun 3, 2018 at 21:42

2 Answers 2


So it's actually to be found in $context['items']

if (($context['items']->getName() != 'field_myfield')) {

// if still here, our field matches. do something

Also note you can be more efficient by using the WIDGET_TYPE hook, e.g. for my "Check boxes/radio buttons" widget:

function hook_field_widget_options_buttons_form_alter(...)

Refer below sample code

function mymodule_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  $field_name = $context['items']->getName();
  $field = FieldConfig::loadByName('node', 'page', $field_name);

  if ($field) {
    $element['#prefix'] = 'hello world';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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