set a entity reference field programmatically I have a node form, with an entity reference field.

I'm trying to hide the reference field from the node form and automatically reference an entity created by the node author.

Im using code like the following to fetch the entity to be referenced.

  $query = new EntityFieldQuery();
  global $user;
  $query-&gt;entityCondition('entity_type', 'node_ref');
  $query-&gt;fieldCondition('cmp_ref', 'target_id', $user-&gt;uid);
  $result = $query-&gt;execute();
  $storeids = array();
  foreach ($result as $ref) {
   foreach ($ref as $ref_id){
    $refids[] = $ref_id-&gt;id;
   }
  }
  $entity = entity_load('node_ref',$refids);
  foreach ($entity as $ref) {
    $ref_id = $ref-&gt;id;
  }
  return $ref_id;


I think its a long way of doing it but I just modified some code I found in a module.

Now upon save of the node I would like the entity reference field to reference $ref_id

So something like

  $node-&gt;entity_reference_field[$node-&gt;language][]['target_id'] = $ref_id;


How do I call this on node submit? If I unset the field on the node form will the value still be set?

Thanks for any help
In case entityreference prepopulate is not a viable option, I always use an EntityMetadataWrapper to set field values.

function mymodule_node_ref_presave($node_ref) {
    global $user;
    $query = new EntityFieldQuery();
    $query-&gt;entityCondition('entity_type', 'node_ref');
    $query-&gt;fieldCondition('cmp_ref', 'target_id', $user-&gt;uid);
    $result = $query-&gt;execute();
    // A more efficient way to grab entity ids from a EFQ
    if($result['node_ref']){
      $ref_ids = array_keys($result['node_ref']);
    }
    if ($ref_ids){
      // Load the entity w/ metadata wrapper to set field more transparently
      $node_ref_wrapper = entity_metadata_wrapper('node', $node_ref);
      $node_ref_wrapper-&gt;entity_reference_field-&gt;set($ref_ids);
      // Because this operation is going to execute a save anyways,
      // we don't need to do $wrapper-&gt;save()
    }
}