I am using organic groups, which creates an entity reference field on a content type. Now i have a custom module that is supposed to create a node programatically and i am having trouble with saving the entity reference field.

Error message i get:Notice: Undefined property: DatabaseStatementBase::$nid

Here is what i have tried:

$qry= db_select('node', 'n')
           ->condition('type', 'some_og_content_type', '=') 
           ->condition('title', 'some_title', '=')
           ->fields('n', array('nid'));
$ogRef= $qry->execute();

$ogNid = $ogRef->nid;

$node->og_group_ref['und'][0] = array('target_id'=>$ogNid);

//i also tried this

1 Answer 1


You need to get the results of your query after $query->execute() by for example calling $query->fetchAssoc() or $query->fetchAllAssoc(..).

Using $node->og_group_ref[LANGUAGE_NONE][0]['target_id'] is correct.

Be aware of the fact that your query might have multiple results. Do something like this to traverse them all:

$result = $query->execute();
while($entry = $result->fetchAssoc()) {
  $node = node_load($entry['nid']);
  // set the field and save the node

Depending on the number of expected entries you could also use EntityFieldQuery explained here https://www.drupal.org/node/1343708.

Another edit: When you want to set a field on a newly created node better use hook_node_presave or hook_node_insert then you do not need to care about searching for your node.

  • thank you! after doing the fetchAssoc(), i was able to get it to work! Mar 25, 2016 at 21:42

Your Answer

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

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