12

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?

4 Answers 4

15

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);
1
  • 8
    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
    Commented Feb 15, 2016 at 18:07
5

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;
}
5

The most simple way to get field config is to use EntityTypeManager.

$entity_type = 'node';// node, taxonomy_term, taxonomy_vocabulary, ...
$bundle = 'article';// the content type machine name
$field = 'field_article_tags';// the field machine name

$fieldConfig =  \Drupal::entityTypeManager()
  ->getStorage('field_config')
  ->load($entity_type . '.' . $bundle . '.' . $field);
1

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 and acknowledge you have read our privacy policy.

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