I'm trying to create an entity that has a number of entity refernce fields, and I'm confused about the best way to do that. so far I've gotten as far as this

$entity = entity_create('mytype', $values);
$entity->field_ref = array('und' => array(0 => array('value' => "2")));

Creating the entity works fine, but I can't for the life of me figure out how to fill in the entity references.


The column name for a field isn't always value; in the case of entity references it's target_id if I remember rightly.

Try this:

$entity = entity_create('mytype', $values);
$entity->field_ref = array('und' => array(0 => array('target_id' => "2")));

Maybe this can help someone:

$entity_ids = array(15,78,45,78);
$count = 0;
foreach ($entity_ids as $id) {
  $node->field_entity_ref[$node->language][$count]['target_id'] = $id;

When using contrib Entity module, you can use entity metadata wrapper syntax, for example:

$entity = entity_create('mytype', array('type' => 'my_bundle'));
try {
  $wrapper = entity_metadata_wrapper('mytype', $entity);
  $wrapper->field_ref = '123';
  $wrapper->field_multi_ref = array('123', '456');
catch (EntityMetadataWrapperException $e) {
  watchdog_exception('my_module', $e);

If you need add new reference to existing entity references .

$counter = 0;
$node_reference = array();
while (!is_null($entity->field_ref['und'][$counter]))
    $node_reference[$counter]= $entity->field_ref['und'][$counter];
$node_reference[$counter]= array('target_id' => $release_nid);
$entity->field_ref= array('und' => $node_reference);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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