Programmatically Creating an Entity Reference Field

Public

The first requirement for programmatically creating an entity reference field is to have the entity reference module installed and enabled. In this example we will be reference a profile2 entity type. We will have a member bundle and we will want to connect an associate member profile to it.

You can place this code in a few different functions depending on how you want it to run. Most people would place it in an update hook or hook_install(),

When creating any field, you must create the field with field_create_field() and attach it to a bundle with field_create_instance(). They should both take the same parameters. If every bundle is going to be the same, you can place most of the information, such as widget, settings, and required, directly to the field. If each bundle will be slightly different you can set any key there so that each entity type will have its own settings.

</> CopyGet raw version
php
  1. $field_name = 'field_linked_associate';
  2.  
  3. // Make sure the field doesn't already exist.
  4. if (!field_info_field($field_name)) {
  5. // Create the field.
  6. $field = array(
  7. 'field_name' => $field_name,
  8. 'type' => 'entityreference',
  9. 'settings' => array(
  10. 'target_type' => 'profile2',
  11. 'handler' => 'base',
  12. 'handler_settings' => array(
  13. 'target_bundles' => array('associate')
  14. ),
  15. ),
  16. );
  17. field_create_field($field);
  18.  
  19. // Create the instance.
  20. $instance = array(
  21. 'field_name' => $field_name,
  22. 'entity_type' => 'profile2',
  23. 'bundle' => 'member',
  24. 'label' => 'Linked Associate',
  25. 'description' => 'Stores a link to the member\'s associated profile.',
  26. 'required' => TRUE,
  27. 'widget' => array(),
  28. 'display' => array(
  29. 'default' => array(
  30. 'label' => 'hidden',
  31. ),
  32. ),
  33. );
  34.  
  35. field_create_instance($instance);
  36. drupal_set_message(t('!field_name was added successfully.', array(
  37. '!field_name' => $field_name,
  38. )));
  39. }

Once the field is created by the script, you can just do a node_load() and set the values there. Remember to always end with a node_save() to save the changes. For example:

</> CopyGet raw version
php
  1. // Assuming the report node is Node 100.
  2. $node = node_load(100);
  3.  
  4. $attached_nodes = array(
  5. 0 => 189,
  6. 1 => 203,
  7. 2 => 405,
  8. 3 => 423,
  9. 4 => 456,
  10. );
  11.  
  12. foreach ($attached_nodes as $attach) {
  13. $node->field_related_reports[LANGUAGE_NONE][] = array(
  14. 'value' => $attach,
  15. );
  16. }
  17.  
  18. // Save the node!
  19. node_save($node);