Download & Extend

Add a Field to an Entity Programmatically

Project:Model Entities
Version:7.x-1.0-alpha2
Component:Documentation
Category:support request
Priority:normal
Assigned:Unassigned
Status:active

Issue Summary

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?

Comments

#1

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();

or
      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
  field_create_field($field);

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
        field_create_instance($field_instance);

you can have a look to http://drupal.org/project/examples there is the node examples that adds fields and instances, it works the same for entities

nobody click here