How do you add a field to the entity in code (programmatically)?

When I install this module I can create entity types each with there own set of fields using the UI, but I need to do it programmatically.

Do you add it to the primary entity or the entity_type entity?

Could you give a code example of that?


keyiyek’s picture

Let say you have all the base code for your entities and entity types up and working,
then you can create a new entity type

      entity_create($type, $values)->save();


      entity_save($type, entity_create($type, $values));

where $type is the name of your entity type and $values is an array with things such label & description.

Then you must define 2 thing: fields and instances.
Field is an array that says the type of data you are going to store, cardinality and other things

    $field = array(
      'field_name' => 'field1',
      'cadinality' => 1,
      'type' => 'number_integer',

once you have defined a field you have to create it


Up to this you just created the field, you have to tell Drupal to wich kind of entities you want it to be attached (even more than one if you like), for this you have to define an instance (properly a field-instance). Again with the arrays:

    $field_instance = array(
      'instance_1' => array(
         'field_name' => 'field1',
         'label' => 'this is an instance for field 1',

after the definition you create it

        // add a couple of info to the instance
        $field_instance['entity_type'] = 'entity1';
        $field_instance['bundle'] = 'entity1_type';
        //create the instance

you can have a look to there is the node examples that adds fields and instances, it works the same for entities

liquidcms’s picture

Issue summary: View changes

i dont think the above for adding an instance works. try this:

$field_instance = array(
 'field_name' => 'field_secondary_programs',
 'label' => 'Secondary Departments',    
 'widget' => array('type' => 'options_buttons'), 
 'entity_type' => 'node',
$field_instance['bundle'] = 'event';
//create the instance
Anybody’s picture

Status: Active » Fixed

Closing this because there was no further feedback from @captaindav. Please tell us how you solved it if possible.
Should this be or is this documented somewhere?

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

shmeterlin’s picture

I'm also trying to figure how to add entities programmatically, the explanation in #1 is very vague. I'm trying to follow the node example but it's not that straight forward when applying here.