2

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.

0

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')->resetCache(array($node->nid));

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

  • I think there is something more becasuse I have added this, and the dpm shows the same. I'm still banging my head on the wall :( – luismagr Mar 6 '14 at 14:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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