To create a new Entity Type simply create an object of the Entity Type class.

$entity_type =  new EntityType();

An entity type is composed of 3 things: name, label, and properties. At minimum, we need to set the name and the label of the entity type.

The name is the machine name for the entity type (letters, numbers, and underscores only, no spaces). This is the main identifier and it should be unique to the system. After the creation of the entity type, we will use this name to interact with our entity types.

The label is the human-readable name, and it is used mainly for GUI displays.

$entity_type->name = "eck_employee";
$entity_type->label = "Employee";

After we get done editing the information in our entity type, we can save it by calling the method save().

$entity_type->save();

I am guessing that you won't want to delete your entity type in the same request that you created it, so if you want to delete your entity type later on (like when your module is being uninstalled) you can do this easily, too.

First, we load the entity type.

$entity_type = EntityType::loadByName('eck_employee');

If you wanted to get all of the entity types created through ECK you can use loadAll().

$entity_types = EntityType::loadAll();

After an entity type is loaded, deleting it is a simple call to the delete method.

$entity_type->delete();

For creating bundles associated to an entity, this is how we can achieve from code:

  // Create bundle for entity
  $entity_type_bundle = new Bundle();
  $entity_type_bundle->name = 'eck_employee';
  $entity_type_bundle->entity_type = 'eck_employee';
  $entity_type_bundle->save();

Comments

nitin.k’s picture

The below code does two jobs.
1. Remove the content associated to bundle.
2. Remove the bundle and associated fields with it as well.


    $custom_entity_type = 'custom_entity';
    $custom_bundle = 'custom_bundle';
    $storage = \Drupal::service('entity_type.manager')->getStorage($custom_entity_type);
    $bundle_key = \Drupal::service('entity_type.manager')->getDefinition($custom_entity_type)->getKey('bundle');
    $entities = $storage->loadByProperties([$bundle_key => $custom_bundle]);
    $storage->delete($entities);

    // Delete the bundle.
    $bundle_type = \Drupal::entityTypeManager()
      ->getStorage($bundle_key)
      ->load($custom_bundle);
    $bundle_type->delete();

Qaiser iqbal’s picture

How to update a bundle field value programatically ? for instance, I have eck entity_type "clinic" and bundle "clinic_location" now i want to update a field of bundle.