How to create Entity Type and Bundle programatically in Drupal 7

How to create Entity Type and Bundle programatically in Drupal 7

Posted byKala,31st Jan 2017

Object Oriented programming (OOP) is mainly associated with the concept of objects which contain data, in the form of fields. Drupal7 also support the OOPs concepts. In Dupal7, the entity type is an abstract base class gives a useful abstraction to group together properties and fields. The Bundle is the extended class for the entity type which provides the implementation of an entity type to which fields can be attached. The fields are the primitive data types which store and retrieve data. An entity is the instance (object) of these base or extended classes.

Entity API module in drupal7 provides an entity CRUD controller to create a new entity. Also, an Entity Construction Kit (ECK) in Drupal7 allows the creation and management of entity types with custom properties With the help of the Field UI module. It helps to add the bundles to entity types as well as fields to bundles too.

we can also create, load and delete the entity type programmatically.

We have to create an object of Entity Type base class, for creating a new entity type. It contains three things name, label, and properties.

// create the an object of Entity Type class
$new_entity_type =  new EntityType();
// add machine name (main identifier) for the new entity type
$entity_type->name = "eck_transaction";
//add label for the for the new entity type
$new_entity_type->label = "transaction";
// save the new entity type

For loading the entitity type, we use

$entity_types = EntityType::loadAll();  // load all the entity type
$entity_type = EntityType::loadByName('eck_transaction'); // load the entity type by name

Also, delete() method used to delete the entity type


Programatically we can also create bundles associated with an entity type.

  // Create an object of Bundle class .
  $bundle = new Bundle();  
  // add name for the bundle
  $bundle->name = 'eck_transaction_log';  
  // specify the associated entity type  
  $bundle->entity_type = 'eck_transaction';  
  // save the bundle