[Drupal] How to add extra field in to an entity?

| | 2 min read

Entities are very important thing in Drupal. Entity type is connected with lot of tables in data type. i.e entity is a object oriented concept. Entities are used to show thw relation ship with different field tables. An entity is a container for bundles. Entities can contain multiple bundles. Examples of an entity are Node, User, File, Taxonomy term, Taxonomy vocabulary.

In a entity creation there is a need of add extra fields in entity. We know in Drupal there is a database table for each fields. So In extra field adding time we should create this database tables with instance table.

So write a function for add extra fields in mymodule.fields.inc


    function mymodule_get_sample_entity_field_data() {
      $sample_entity_fields = array(
        'sample_field' => array(
          'field' => array(
            'field_name' => 'Title',
            'entity_types' => array('sample_entity'),
            'cardinality' => 1,
            'type' => 'text',
            'settings' => array('max_length' => 255),
          ),
          'instance' => array(
            'field_name' => 'sample_field',
            'label' => t('sample_entity_sample_field'),
            'entity_type' => 'sample_entity',
            'bundle' => '',
            'description' => 'status note of milestone planning.',
          )
      ),
    );
    return $sample_entity_fields;
  } 

Then call the above function for create the field and instances of corresponding fields.


  function mymodule_create_sample_entity_fields() {
  // Define field and field instances.
  $sample_entity_fields = mymodule_get_sample_entity_field_data();
  foreach ($sample_entity_fields as $field_data) {
    $field = $field_data['field'];
    // Create field if not exists.
    if (!field_read_field($field['field_name'], array('include_inactive' => TRUE))) {
      field_create_field($field)entity_save('sample_entity', $sample_entity);;
    }
    $instance = $field_data['instance'];
    // Create field instance if not exists.
    if (!field_read_instance($instance['entity_type'], $instance['field_name'], $instance['bundle'], array('include_inactive' => TRUE))) {
      field_create_instance($instance);
    }
  } 

The above function is also written in mymodule.fields.inc

Finally we add these functions in entity creation module then we can add the extra fields in entity successfully.