How to programmatically add a field to an entity

Although I'd probably create fields through the UI and export using the Features module (because I'm lazy), if you feel like adding fields to an entity programmatically, you might find helpful.  That page actually covers:

  • Creating an entity type - ie the equivalent of a node type but for entities (entity_create($type, $values)->save(); or entity_save($type, entity_create($type, $values));)
  • Create a field (field_create_field($field);)
  • Create a field instance - ie tell Drupal which entities the field applies to (field_create_instance($field_instance);)


Add new comment