2

maybe my title is not correct but I have written a module that creates a new entity. Now I would like to create a few of these entities on hook_install. I can create a new entity, that's not the problem, but I cannot create the entity types.

This is my code I use to create a new entity:

/**
 * Implements hook_install()
 */
function skilt_badge_install(){
  $entity = entity_create('skilt_badge', array('type' =>'test'));
  $entity->title = "Testtitle";
  $entity->description = "Testdescription";
  $entity->save();
}

Now, when I create a new Skilt badge type with the machine name "test" in the drupal interface it works. But first I would like to know how I create the Skilt badge type programmatically.

I've tried something like this first, thinking the type is also an entity:

/**
 * Implements hook_install()
 */
function skilt_badge_install(){
  $entity = entity_create('skilt_badge_type');
  $entity->title = "Testtitle";
  $entity->description = "Testdescription";
  $entity->save();
}

But that didn't really work because entity create requires a type...

Could you guys help me?

  • There's quite a lot to it, the best place to start is the Examples module; it has an entity example module which has plenty of example code – Clive Jul 11 '15 at 22:39
  • The answer to this question could be turned into a book almost so if you want a full tutorial on spinning up custom entities and creating them you can follow this: sitepoint.com/build-custom-entities-drupal-setup and take a look at the Drupal examples project: drupal.org/project/examples to see other code. Those should give you a better understanding on how to go about what you are trying to accomplish. – burnsjeremy Jul 11 '15 at 22:46
  • Have you created the entity type "test" already? That is not a standard Drupal entity type is why I ask. – Brady Jul 12 '15 at 8:10
  • Creating the type "test" is my issue. I don't know how to do that. My first block of code works and creates an entity of type "test" with title "Testtitle" and description "Testdescription". I can create the entity type "test" in the drupal interface but I would like to do that programmatically. – Jens Rentmeesters Jul 12 '15 at 12:06
1

As some have commented, Entities are VERY complicated. The reason your code is not working is because entity_create() is used to create an INSTANCE of an entity of an already defined entity type. What you are doing in the UI creates the entity type.

You must first create your entity type in your module before you can create an instance of that entity. Refer to the links in the comments above on how to do this. And get ready to spend a little time if this is your first time doing this -I assume it is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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