Drupal 7 Add Node to Organic Group (OG) programmatically
Needed an easy way to add content into an organic group using Drupal 7. I ended up using the og_group function provided by Organic Groups (in the og.module file). Here is the quick solution that worked for me.
//Get the group id $gid = 25; //Get the full node that needs to be subscribed to the group $node = node_load(17); //Set the values $values = array( 'entity_type' => 'node', 'entity' => $node, 'state' => OG_STATE_ACTIVE, ); //Add this node to the group $result = og_group('node', $gid, $values);



Discussions
how do we get the $gid
how do we get the $gid
$gid value
The $gid value is just the node id of the group node. If you go to the group page and click on the edit link for that group content, you can pull the node id (also the $gid) from the URL. You can also get this value from the node table in the database.
I assume that the the content
I assume that the the content type has to be a group to do this does the above code change the group_group field value to ON as well or should we do that manually
or can we update the node's group_group field and save the node
Group content type
I believe the content type needs to be a group in order for this to work. The content you are posting into the group should also be set up so that the content can be posted into the group. I believe all this is configuration on the content type settings page or each content type.
didn't work for me,
needn't node_save()?
here is my code:
$group_type ='node';
$gid = 104;
$entity = node_load(274);
$values = array(
'entity type' => 'node',
'entity' => $entity);
//og_is_member($group_type, $gid, $entity_type = 'user', $entity = NULL, $states = array(OG_STATE_ACTIVE))
$is_member_before = og_is_member($group_type, $gid, $entity_type = 'node', $entity, $states = array(OG_STATE_ACTIVE)) ;
dpm('is_member_before', var_export($is_member_before,true));
og_group('node',$gid, $values);
//function og_group($group_type, $gid, $values = array())
node_save($entity);
$is_member_before = og_is_member($group_type, $gid, $entity_type = 'node', $entity, $states = array(OG_STATE_ACTIVE)) ;
dpm('is_member_after', var_export($is_member_before,true));
organic group module
Hi Shane,
I'm really enjoying the daily dose of drupal videos!
May you please cover organic group 7.2 module and group layout setup?
I have seen multiple videos on that topic but all were pretty confusing for me.
Thanks, Yool
How would you do this when
How would you do this when creating a node programmatically and don't know the nid?
Post new comment