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->type); if ($type == 'content_type1' || $type == 'content_type2'){ // Get the user $user = user_load($node->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' => 'node', 'entity' => $node, 'field_name' => 'og_group_ref', 'state' => 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(&$form, &$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.
Sponsored by SupremePR