Auto assign organic group to a content type I'm trying to assign the group audience to a content type at creation instant. The first thing I have done is to disable the group audience field. So I have implemented the hook_form_alter and done this:

$form['og_group_ref']['#access']= false;


Then, I have implemented the hook_node_insert and here is where I have tried to assign the group. In my use case, users can only have one group. That's my code:

/**
 * Implements hook_node_insert
 */
function og_autoassign_node_insert($node){
  //Get the type
  $type = is_string($node) ? $node : (is_array($node) ? $node['type'] : $node-&gt;type);

  if ($type == 'content_type1' || $type == 'content_type2'){
    // Get the user
    $user = user_load($node-&gt;uid);

    // Load the current user's group
    //$groups = og_get_entity_groups('user', $user);
    $groups = og_get_groups_by_user($user);

    // Load the GID
    $group_id;
    foreach(array_keys($groups['node']) as $id){
        $group_id = $id;
    }

    $values = array(  
        'entity_type' =&gt; 'node',
        'entity' =&gt; $node,
        'field_name' =&gt; 'og_group_ref',
        'state' =&gt; OG_STATE_ACTIVE
    );
    og_group('node', $group_id, $values);

    dpm($node);
  }
}


When I print the node with dpm, I can not see the organic group associated. What I'm doing wrong? Can anyone help me?

Thanks a lot

UPDATE (I can't answer myself because I have less than 10 in reputation)

Well, I found one solution. Instead of implementing the hook_node_insert, I did that in my hook_form_alter:

function my_module_form_alter(&amp;$form, &amp;$form_state, $form_id){
...
// Load the current user's group
$groups = og_get_groups_by_user();

$form['og_group_ref']['und'][0]['default']['#default_value'] = $groups['node'];
}


And that set the field "Audience Group" with the user's group.
I just ran into this problem with hooks. It's being saved but you won't see this in node_insert due to the caching system of nodes in Drupal. Add this before your dpm code and you'll see the results immediately.

entity_get_controller('node')-&gt;resetCache(array($node-&gt;nid));


I'm so happy I can stop someone else from banging their head on the wall like I did. Ha.