4

Is there a way to create an entity reference in hook_entity_info? I was hoping for something like the following.

'entity keys' => array(
  'id' => 'id',
  'store_ref_id' => 'store_ref_id',
), 

I have a content type store with its ID, and a new entity_type product. I would like to have a field in the new entity referenced to content type.

How can I do this?

Would it be better to re-use the already created field, which is used as reference between content types?

1

1 Answer 1

7

You can attach this field like any other:

function MY_MODULE_install() {
  // Create a field for company reference to be used by various entities
  $field = array(
    'field_name' => 'company_reference',
    'type' => 'entityreference',
    'settings' => array(
      'target_type' => 'company',
      'handler_settings' => array('target_bundles' => NULL),
    ),
    'cardinality' => 1,
    'translatable' => FALSE,
  );
  field_create_field($field);

  // Attach the company reference field to employee instance
  $instance = array(
    'field_name' => 'company_reference',
    'entity_type' => 'employee',
    'bundle' => 'employee',
    'label' => 'Company',
    'required' => false,
    'widget' => array(
      'type' => 'options_select'
    ),
    'settings' => array(
      'target_type' => 'company',
      'handler_settings' => array('target_bundles' => NULL),
    ),
    'display' => array(
      'default' => array('label' => 'inline', 'type' => 'entityreference_label'),
    ),
  );
  field_create_instance($instance);
}

Code sample taken from this more comprehensive manual.

2
  • Do you know what is the easiest way to create admin ui? I would like to have list of all new entities and add/edit/delete actions availabe. Just like at content types.
    – gregab
    Commented Jul 1, 2013 at 9:00
  • 1
    You mean like this? And please ask questions as questions.
    – Mołot
    Commented Jul 1, 2013 at 9:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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