1

I am trying to get the custom fields created for the User entity in Drupal 8.

  • Drupal::service('entity_field.manager')->getFieldStorageDefinitions('user') returns all the fields
  • Drupal::service('entity_field.manager')->getFieldDefinitions('user', '') returns only the default fields

My code creates the list by removing the fields returned from getFieldDefinitions('user', '') by the fields returned from getFieldDefinitions('user'.

Is there a proper way to achieve this?

1
  • Please, define 'custom fields'.
    – ya.teck
    Commented Mar 31, 2019 at 14:42

1 Answer 1

4

You can filter the fields by checking which interface the field implements:

$fields = array_filter(
  \Drupal::service('entity_field.manager')->getFieldDefinitions('user', 'user'),
  function ($fieldDefinition) {
    return $fieldDefinition instanceof \Drupal\field\FieldConfigInterface;
  }
);

The second parameter of getFieldDefinitions() is the bundle. The user entity doesn't have bundles, but you can configure bundle fields. In this case the bundle name defaults to the entity id.

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.