0

I am using Drupal 8.4. I am trying to dynamically create/update field data for a content type.

Is there a way to get the type of a field (e.g. text, image, file upload) for a content type?

1

You can obtain the field type using Entity field manager.

$definitions = \Drupal::service('entity_field.manager')
  ->getFieldStorageDefinitions('node');

$field_type = $definitions['field_image']->getType();
  • 2
    That works, but depending on what you are working with, there are easier ways, e.g. when you already have an entity object, you can just do $entity->getFieldDefinition('field_image')->getType() – Berdir Feb 5 '18 at 15:32
  • Its not working. It gave an Unexpected error "The website encountered an unexpected error. Please try again later.</br></br><em class="placeholder">Drupal\Component\Plugin\Exception\PluginNotFoundException</em>: The &quot;article_text&quot; entity type does not exist. in <em class="placeholder">Drupal\Core\Entity\EntityTypeManager-&gt;getDefinition()</em> (line <em class="placeholder">133</em> of <em class="placeholder">core\lib\Drupal\Core\Entity\EntityTypeManager.php</em>)." – Kiran Feb 6 '18 at 6:57
  • Here the solution is provided for generic node; instead I want to make it work for a content type. – Kiran Feb 6 '18 at 8:49
  • 1
    @Kiran a content type is a variant of a node. field storages are the same for all nodes, they just might or might not exist on a certain content type/bundle. That means for the type, you don't need article_text, you just need node. Only if you need something like the lable then you need to call getFieldDefinitions() which has two arguments, entity type and bundle – Berdir Feb 7 '18 at 16:19

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