Creating D7 OG groups programmatically

This is a crosspost to a D.o issue I replied to since I recently had to create groups programmatically in Drupal 7.

Drupal 6/7 have drupal_execute() for D6 and drupal_form_submit() for D7 to programmatically submit forms. If you install OG and create a content type for your groups -- you can then programmatically submit the form via a Drush script or a module update using core drupal functions.

An example of inspecting, and how to understand a POST of node creation form and also using drupal_form_submit() can be found here, and some nifty Firebug usage: Programmatically create nodes tutorial

As an example the php script I created and then ran via "drush php-script" was as follows to create about a dozen groups on-the-fly in D7:

/*
 * Eg filename "make-groups.php"
 * run via "drush -l {SITENAME_URI} php-script make-groups.php
 */

/* include this if you run this within a module to assure * the node_form() functions have been included for the code * you're about to run ... */ module_load_include('inc', 'node', 'node.pages');

/* groups to create. */ $areas = array( 'group1', 'group2', 'group3', );

foreach ($areas as $area) { $form_state = array(); /* these are essentially cookie-cutter fields shared by most * any node type. */ $form_state['values']['body']['und'][0]['format'] = 2; $form_state['values']['body']['und'][0]['summary'] = ''; $form_state['values']['body']['und'][0]['value'] = ''; $form_state['values']['book']['bid'] = 0; $form_state['values']['book']['plid'] = -1; $form_state['values']['book']['weight'] = 0; $form_state['values']['changed'] = ''; $form_state['values']['date'] = ''; $form_state['values']['log'] = ''; $form_state['values']['op'] = t('Save'); $form_state['values']['path']['alias'] = ''; $form_state['values']['revision'] = 1; $form_state['values']['status'] = 1; $form_state['values']['language'] = LANGUAGE_NONE;

/* these are the 2 fields that we actually care about for groups. */
$form_state['values']['title'] = $area;
$form_state['values']['group_group']['und'] = 1;

$newNode = new stdClass();
/* the machine name of the OG group you created. */
$newNode->type = "idgroup";
$newNode->language= LANGUAGE_NONE;
$newNode->options = array();
$newNode->uid = 1;
$newNode->promote = 0;
$newNode->module = 'node';
node_object_prepare($newNode);

/* Call your content type's node create form passing a
 * canned $form_state and a bare-bones node object.
 */
drupal_form_submit('idgroup_node_form', $form_state, $newNode);

}

2011 © Copyright David Gurba метр
Powered by Drupal