8

What's the equivalent of field_info_instance() for Drupal 8?

The default field settings are stored as configuration in a file like field.field.ENTITYTYPE.BUNDLE.FIELDNAME.yml, but how do I get their current value?

9

Using the entity_field.manager service, you are able to get an array of BaseFieldDefinition classes. This service is injectable as well, but for copy-paste working code, you can do the following:

$bundle_fields = \Drupal::getContainer()->get('entity_field.manager')->getFieldDefinitions($entity_type, $bundle);
$field_definition = $bundle_fields[$field_name];
$catalog_id = $field_definition->getSetting($setting_name);
  • 4
    If you have an entity and are working with that, you can also access the field definitions of your entity object with $entity->getFieldDefinitions(). – Berdir Feb 15 '16 at 18:07
2

Using a field instance:

$settings = $field->getFieldDefinition()->getSettings();

For example, in a field widget:

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  $element = [];

  // Get the settings.
  $settings = $items[$delta]->getFieldDefinition()->getSettings();

  // ... build render array

  return $element;
}
0

I wanted to get the Type and Label from the field definition. This did not work:

$setting_name = 'label';
$label = $field_definition->getSetting($setting_name);

This worked:

$label = $field_definition->getLabel();
$type = $field_definition->getType();

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.