/**
 * Implements hook_node_view_alter().
 */
function CUSTOM_node_view_alter(&$build) {
  // When adding a new child page to a book in a group, prepopulate the child page's group field.
  if ($build['#entity_type'] == 'node' && $build['#bundle'] == 'book') {
    if (isset($build['links']['book']['#links']['book_add_child'])) {
      if ($group = og_context()) {
        $build['links']['book']['#links']['book_add_child']['query']['og_group_ref'] = $group['gid'];
      }
    }
  }
}

/**
 * Implements hook_form_book_node_form_alter().
 */
function CUSTOM_form_book_node_form_alter(&$form, &$form_state) {
  // Limit book choices to those in the group context during node creation
  // and those that the user can edit.
  $options = $form['book']['bid']['#options'];
  // Check each option.
  foreach ($options as $key => $value) {
    $groups = array();
    if (is_numeric($key) && $key) {
      $book = node_load($key);
      if ($group = og_context() && !$form['nid']['#value']) {
        // Get the groups this book is in.
        $items = field_get_items('node', $book, 'og_group_ref');
        foreach ($items as $item) {
          $groups[$item['target_id']] = 1;
        }
        // Remove the option if its groups do not include the group context.
        if (!isset($groups[$group['gid']])) {
          unset($options[$key]);
        }
      }
      if (!node_access('update', $book)) {
        unset($options[$key]);
      }
    }
  }
  $form['book']['bid']['#options'] = $options;
}

Comments

mxr576’s picture

Category: Task » Feature request

This looks like a feature request to me and your code requires og_context.module to be enabled. Besides, maybe this is out of scope of this module and it should be handled in book_helper.module somehow for example. I'll think about this.

mxr576’s picture

Title: D7 Sample Code » Prepopulate group field when adding a new child page to a group's book
Component: Documentation » Code