2

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->entityCondition('entity_type', 'node_ref');
  $query->fieldCondition('cmp_ref', 'target_id', $user->uid);
  $result = $query->execute();
  $storeids = array();
  foreach ($result as $ref) {
   foreach ($ref as $ref_id){
    $refids[] = $ref_id->id;
   }
  }
  $entity = entity_load('node_ref',$refids);
  foreach ($entity as $ref) {
    $ref_id = $ref->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->entity_reference_field[$node->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

2 Answers 2

7

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->entityCondition('entity_type', 'node_ref');
    $query->fieldCondition('cmp_ref', 'target_id', $user->uid);
    $result = $query->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->entity_reference_field->set($ref_ids);
      // Because this operation is going to execute a save anyways,
      // we don't need to do $wrapper->save()
    }
}
2

You can use the module Entity reference prepopulate. It's doing exactly what you need - hide the field if you want, fill it with values from the address/callback function or you can write your own pre populate plugin. It's even integrate with the OG module.

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.