3

I am creating a node programatically and one of the fields in the node is an entity reference field referencing a user.

I am using the guide from https://www.drupal.org/node/1388922 and the general consensus i gather is that I need to do something like;

$node->field_customer_nid[$node->language][] = array(
'target_id' => $form_state['values']['entity id'],
'target_type' => 'node',

);

My question is where do i pass the values for the target entity(basically the uid)in that array. Is it the target_id or the entity_id because my attempts with either of those is not working.

0

The better approach is using entity metadata wrapper.

Below snippet is copied from drupal.org documentation

$containing_node = node_load($nid);
$w_containing_node = entity_metadata_wrapper('node', $containing_node);

$nids_to_set = array(42, 23);
$w_containing_node->field_entity_reference_field->set($nids_to_set);
0

You have to specify the entity id and the entity type. The example is referencing a node but you want to reference a user.

Try this:

$node->field_customer_nid[$node->language][] = array(
  'target_id' => $entity_id,
);

$entity_id should hold the referenced entity id.

  • 2
    That's not quite right - there's only one field column (target_id), the target type is a setting for the whole field and can't be set at runtime so-to-speak. Just providing a valid entity id for target_id is all that's necessary – Clive Jun 23 '14 at 12:14
  • Oops, sorry, I didn't check it... as is a wrng answer I'm going to delete it, do you want to repost your comment in the question or as a new answer? – sanzante Jun 23 '14 at 15:35

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.