Projet

Général

Profil

Paste
Télécharger (76,8 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / field_group / field_group.module @ e9f59589

1
<?php
2

    
3
/**
4
 * @file
5
 * Fieldgroup module.
6
 *
7
 * For an overview of all php and javascript hooks, see field_group.api.php.
8
 *
9
 */
10

    
11
/**
12
 * Implements hook_menu().
13
 */
14
function field_group_menu() {
15
  $items = array();
16

    
17
  // Ensure the following is not executed until field_bundles is working and
18
  // tables are updated. Needed to avoid errors on initial installation.
19
  if (defined('MAINTENANCE_MODE')) {
20
    return $items;
21
  }
22

    
23
  // Create tabs for all possible bundles.
24
  foreach (entity_get_info() as $entity_type => $entity_info) {
25
    if (isset($entity_info['fieldable']) && $entity_info['fieldable']) {
26
      foreach ($entity_info['bundles'] as $bundle_name => $bundle_info) {
27
        if (isset($bundle_info['admin'])) {
28
          // Extract path information from the bundle.
29
          $path = $bundle_info['admin']['path'];
30
          // Different bundles can appear on the same path (e.g. %node_type and
31
          // %comment_node_type). To allow field_group_menu_load() to extract the
32
          // actual bundle object from the translated menu router path
33
          // arguments, we need to identify the argument position of the bundle
34
          // name string ('bundle argument') and pass that position to the menu
35
          // loader. The position needs to be casted into a string; otherwise it
36
          // would be replaced with the bundle name string.
37
          if (isset($bundle_info['admin']['bundle argument'])) {
38
            $bundle_arg = $bundle_info['admin']['bundle argument'];
39
            $bundle_pos = (string) $bundle_arg;
40
          }
41
          else {
42
            $bundle_arg = $bundle_name;
43
            $bundle_pos = '0';
44
          }
45

    
46
          // This is the position of the %field_group_menu placeholder in the
47
          // items below.
48
          $group_position = count(explode('/', $path)) + 1;
49

    
50
          // Extract access information, providing defaults.
51
          $access = array_intersect_key($bundle_info['admin'], drupal_map_assoc(array('access callback', 'access arguments')));
52
          $access += array(
53
            'access callback' => 'user_access',
54
            'access arguments' => array('administer site configuration'),
55
          );
56

    
57
          $items["$path/groups/%field_group_menu/delete"] = array(
58
            'load arguments' => array($entity_type, $bundle_arg, $bundle_pos, '%map'),
59
            'title' => 'Delete',
60
            'page callback' => 'drupal_get_form',
61
            'page arguments' => array('field_group_delete_form', $group_position),
62
            'type' => MENU_CALLBACK,
63
            'file' => 'field_group.field_ui.inc',
64
          ) + $access;
65

    
66
          $items["$path/groups/%field_group_menu/enable"] = array(
67
            'load arguments' => array($entity_type, $bundle_arg, $bundle_pos, '%map'),
68
            'title' => 'Enable',
69
            'page callback' => 'drupal_get_form',
70
            'page arguments' => array('field_group_enable_form', $group_position),
71
            'type' => MENU_CALLBACK,
72
            'file' => 'field_group.field_ui.inc',
73
          ) + $access;
74

    
75
        }
76
      }
77
    }
78
  }
79

    
80
  return $items;
81
}
82

    
83
/**
84
 * Implements hook_permission().
85
 */
86
function field_group_permission() {
87
  return array(
88
    'administer fieldgroups' => array(
89
      'title' => t('Administer fieldgroups'),
90
      'description' => t('Display the administration for fieldgroups.'),
91
    ),
92
  );
93
}
94

    
95
/**
96
 * Menu Wildcard loader function to load group definitions.
97
 *
98
 * @param $group_name
99
 *   The name of the group, as contained in the path.
100
 * @param $entity_type
101
 *   The name of the entity.
102
 * @param $bundle_name
103
 *   The name of the bundle, as contained in the path.
104
 * @param $bundle_pos
105
 *   The position of $bundle_name in $map.
106
 * @param $map
107
 *   The translated menu router path argument map.
108
 */
109
function field_group_menu_load($group_name, $entity_type, $bundle_name, $bundle_pos, $map) {
110

    
111
  if ($bundle_pos > 0) {
112
    $bundle = $map[$bundle_pos];
113
    $bundle_name = field_extract_bundle($entity_type, $bundle);
114
  }
115

    
116
  $args = func_get_args();
117
  $args_pop = array_pop($args);
118
  $mode = array_pop($args_pop);
119

    
120
  $group = field_group_load_field_group($group_name, $entity_type, $bundle_name, $mode);
121

    
122
  return empty($group) ? FALSE : $group;
123
}
124

    
125
/**
126
 * Loads a group definition.
127
 *
128
 * @param $group_name
129
 *   The name of the group.
130
 * @param $entity_type
131
 *   The name of the entity.
132
 * @param $bundle_name
133
 *   The name of the bundle.
134
 * @param $mode
135
 *   The view mode to load.
136
 */
137
function field_group_load_field_group($group_name, $entity_type, $bundle_name, $mode) {
138

    
139
  ctools_include('export');
140
  $objects = ctools_export_load_object('field_group', 'conditions', array(
141
    'group_name' => $group_name,
142
    'entity_type' => $entity_type,
143
    'bundle' => $bundle_name,
144
    'mode' => $mode,
145
  ));
146
  $object = array_shift($objects);
147

    
148
  if ($object && isset($object->data)) {
149
    return field_group_unpack($object);
150
  }
151

    
152
  return $object;
153
}
154

    
155
/**
156
 * Implements hook_ctools_plugin_api().
157
 */
158
function field_group_ctools_plugin_api($owner, $api) {
159
  if ($owner == 'field_group' && $api == 'field_group') {
160
    return array('version' => 1);
161
  }
162
}
163

    
164
/**
165
 * Implements hook_theme().
166
 */
167
function field_group_theme() {
168
  return array(
169
    'horizontal_tabs' => array(
170
      'render element' => 'element',
171
    ),
172
    'multipage' => array(
173
      'render element' => 'element',
174
    ),
175
    'multipage_pane' => array(
176
      'render element' => 'element',
177
    ),
178
  );
179
}
180

    
181
/**
182
 * Implements hook_theme_registry_alter().
183
 */
184
function field_group_theme_registry_alter(&$theme_registry) {
185

    
186
  // Inject field_group_build_entity_groups in all entity theming functions.
187
  $entity_info = entity_get_info();
188
  $entities = array();
189
  foreach ($entity_info as $entity => $info) {
190
    if (isset($entity_info[$entity]['fieldable']) && $entity_info[$entity]['fieldable']) {
191
      // User uses user_profile for theming.
192
      if ($entity == 'user') $entity = 'user_profile';
193
      $entities[] = $entity;
194
    }
195
  }
196

    
197
  // Support for File Entity.
198
  if (isset($theme_registry['file_entity'])) {
199
    $entities[] = 'file_entity';
200
  }
201

    
202
  // Support for Entity API.
203
  if (isset($theme_registry['entity'])) {
204
    $entities[] = 'entity';
205
  }
206

    
207
  foreach ($entities as $entity) {
208
    if (isset($theme_registry[$entity])) {
209
      $theme_registry[$entity]['preprocess functions'][] = 'field_group_build_entity_groups';
210
      // DS support, make sure it comes after field_group.
211
      if ($key = array_search('ds_entity_variables', $theme_registry[$entity]['preprocess functions'])) {
212
        unset($theme_registry[$entity]['preprocess functions'][$key]);
213
        $theme_registry[$entity]['preprocess functions'][] = 'ds_entity_variables';
214
      }
215
    }
216
  }
217

    
218
}
219

    
220
/**
221
 * Implements hook_field_attach_delete_bundle().
222
 *
223
 * @param String $entity_type
224
 * @param String $bundle
225
 */
226
function field_group_field_attach_delete_bundle($entity_type, $bundle) {
227

    
228
  ctools_include('export');
229
  $list = field_group_read_groups(array('bundle' => $bundle, 'entity_type' => $entity_type));
230

    
231
  // Delete the entity's entry from field_group of all entities.
232
  // We fetch the field groups first to assign the removal task to ctools.
233
  if (isset($list[$entity_type], $list[$entity_type][$bundle])) {
234
    foreach ($list[$entity_type][$bundle] as $group_mode => $groups) {
235
      foreach ($groups as $group) {
236
        ctools_export_crud_delete('field_group', $group);
237
      }
238
    }
239
  }
240

    
241
}
242

    
243
/**
244
 * Implements hook_field_attach_form().
245
 */
246
function field_group_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
247

    
248
  $form['#attached']['css'][] = drupal_get_path('module', 'field_group') . '/field_group.field_ui.css';
249
  field_group_attach_groups($form, 'form', $form_state);
250
  $form['#pre_render'][] = 'field_group_form_pre_render';
251
}
252

    
253
/**
254
 * Implements hook_form_FORM_ID_alter().
255
 * Using hook_form_field_ui_field_overview_form_alter.
256
 */
257
function field_group_form_field_ui_field_overview_form_alter(&$form, &$form_state) {
258
  form_load_include($form_state, 'inc', 'field_group', 'field_group.field_ui');
259
  field_group_field_ui_overview_form_alter($form, $form_state);
260
}
261

    
262
/**
263
 * Implements hook_form_FORM_ID_alter().
264
 * Using hook_form_field_ui_display_overview_form_alter.
265
 */
266
function field_group_form_field_ui_display_overview_form_alter(&$form, &$form_state) {
267
  form_load_include($form_state, 'inc', 'field_group', 'field_group.field_ui');
268
  field_group_field_ui_overview_form_alter($form, $form_state, TRUE);
269
}
270

    
271
/**
272
 * Implements hook_field_attach_view_alter().
273
 */
274
function field_group_field_attach_view_alter(&$element, $context) {
275
  // Check whether the view mode uses custom display settings or the 'default' mode.
276
  $actual_mode = 'default';
277
  if (isset($element['#entity_type']) && isset($element['#bundle'])) {
278
    $view_mode_settings = field_view_mode_settings($element['#entity_type'], $element['#bundle']);
279
    $view_mode = $context['view_mode'];
280
    $actual_mode = (!empty($view_mode_settings[$view_mode]['custom_settings']) ? $view_mode : 'default');
281
    field_group_attach_groups($element, $actual_mode);
282
  }
283
}
284

    
285
/**
286
 * Implements hook_field_group_formatter_info().
287
 */
288
function field_group_field_group_formatter_info() {
289

    
290
  return array(
291
    'form' => array(
292
      'html-element' => array(
293
        'label' => t('HTML element'),
294
        'description' => t('This fieldgroup renders the inner content in a HTML element with classes and attributes.'),
295
        'instance_settings' => array('element' => 'div', 'show_label' => 0, 'label_element' => 'div', 'classes' => '', 'attributes' => '', 'required_fields' => 1),
296
      ),
297
      'div' => array(
298
        'label' => t('Div'),
299
        'description' => t('This fieldgroup renders the inner content in a simple div with the title as legend.'),
300
        'format_types' => array('open', 'collapsible', 'collapsed'),
301
        'instance_settings' => array('description' => '', 'show_label' => 1, 'label_element' => 'h3', 'effect' => 'none', 'speed' => 'fast', 'classes' => '', 'required_fields' => 1, 'id' => ''),
302
        'default_formatter' => 'open',
303
      ),
304
      'html5' => array(
305
        'label' => t('HTML5'),
306
        'description' => t('This fieldgroup renders the inner content in a semantic HTML5 wrapper'),
307
        'instance_settings' => array('wrapper' => '', 'classes' => '', 'id' => ''),
308
      ),
309
      'fieldset' => array(
310
        'label' => t('Fieldset'),
311
        'description' => t('This fieldgroup renders the inner content in a fieldset with the title as legend.'),
312
        'format_types' => array('open', 'collapsible', 'collapsed'),
313
        'instance_settings' => array('description' => '', 'classes' => '', 'required_fields' => 1),
314
        'default_formatter' => 'collapsible',
315
      ),
316
      'tabs' => array(
317
        'label' => t('Vertical tabs group'),
318
        'description' => t('This fieldgroup renders child groups in its own vertical tabs wrapper.'),
319
        'instance_settings' => array('classes' => ''),
320
      ),
321
      'tab' => array(
322
        'label' => t('Vertical tab'),
323
        'description' => t('This fieldgroup renders the content in a fieldset, part of vertical tabs group.'),
324
        'format_types' => array('open', 'closed'),
325
        'instance_settings' => array('description' => '', 'classes' => '', 'required_fields' => 1),
326
        'default_formatter' => 'closed',
327
      ),
328
      'htabs' => array(
329
        'label' => t('Horizontal tabs group'),
330
        'description' => t('This fieldgroup renders child groups in its own horizontal tabs wrapper.'),
331
        'instance_settings' => array('classes' => ''),
332
      ),
333
      'htab' => array(
334
        'label' => t('Horizontal tab'),
335
        'format_types' => array('open', 'closed'),
336
        'description' => t('This fieldgroup renders the content in a fieldset, part of horizontal tabs group.'),
337
        'default_formatter' => 'closed',
338
        'instance_settings' => array('description' => '', 'classes' => '', 'required_fields' => 1, 'id' => ''),
339
      ),
340
      'multipage-group' => array(
341
        'label' => t('Multipage group'),
342
        'description' => t('This fieldgroup renders groups on separate pages.'),
343
        'instance_settings' => array('classes' => '', 'page_header' => 3, 'move_additional' => 1, 'page_counter' => 1, 'move_button' => 0),
344
      ),
345
      'multipage' => array(
346
        'label' => t('Multipage'),
347
        'format_types' => array('start', 'no-start'),
348
        'description' => t('This fieldgroup renders the content in a page.'),
349
        'default_formatter' => 'no-start',
350
        'instance_settings' => array('description' => '', 'classes' => '', 'required_fields' => 1),
351
      ),
352
      'accordion' => array(
353
        'label' => t('Accordion group'),
354
        'description' => t('This fieldgroup renders child groups as jQuery accordion.'),
355
        'instance_settings' => array('effect' => 'none', 'classes' => ''),
356
      ),
357
      'accordion-item' => array(
358
        'label' => t('Accordion item'),
359
        'format_types' => array('open', 'closed'),
360
        'description' => t('This fieldgroup renders the content in a div, part of accordion group.'),
361
        'default_formatter' => 'closed',
362
        'instance_settings' => array('description' => '', 'classes' => '', 'required_fields' => 1),
363
      ),
364
    ),
365
    'display' => array(
366
      'html-element' => array(
367
        'label' => t('HTML element'),
368
        'description' => t('This fieldgroup renders the inner content in a HTML element with classes and attributes.'),
369
        'instance_settings' => array('element' => 'div', 'show_label' => 0, 'label_element' => 'div', 'classes' => '', 'attributes' => '', 'required_fields' => 1),
370
      ),
371
      'div' => array(
372
        'label' => t('Div'),
373
        'description' => t('This fieldgroup renders the inner content in a simple div with the title as legend.'),
374
        'format_types' => array('open', 'collapsible', 'collapsed'),
375
        'instance_settings' => array('description' => '', 'show_label' => 1, 'label_element' => 'h3', 'effect' => 'none', 'speed' => 'fast', 'classes' => '', 'id' => ''),
376
        'default_formatter' => 'collapsible',
377
      ),
378
      'html5' => array(
379
        'label' => t('HTML5'),
380
        'description' => t('This fieldgroup renders the inner content in a semantic HTML5 wrapper'),
381
        'instance_settings' => array('wrapper' => '', 'classes' => '', 'id' => ''),
382
      ),
383
      'fieldset' => array(
384
        'label' => t('Fieldset'),
385
        'description' => t('This fieldgroup renders the inner content in a fieldset with the title as legend.'),
386
        'format_types' => array('open', 'collapsible', 'collapsed'),
387
        'instance_settings' => array('description' => '', 'classes' => ''),
388
        'default_formatter' => 'collapsible',
389
      ),
390
      'tabs' => array(
391
        'label' => t('Vertical tabs group'),
392
        'description' => t('This fieldgroup renders child groups in its own vertical tabs wrapper.'),
393
        'instance_settings' => array('classes' => ''),
394
      ),
395
      'tab' => array(
396
        'label' => t('Vertical tab'),
397
        'description' => t('This fieldgroup renders the content in a fieldset, part of vertical tabs group.'),
398
        'format_types' => array('open', 'closed'),
399
        'instance_settings' => array('description' => '', 'classes' => ''),
400
        'default_formatter' => 'closed',
401
      ),
402
      'htabs' => array(
403
        'label' => t('Horizontal tabs group'),
404
        'description' => t('This fieldgroup renders child groups in its own horizontal tabs wrapper.'),
405
        'instance_settings' => array('classes' => ''),
406
      ),
407
      'htab' => array(
408
        'label' => t('Horizontal tab item'),
409
        'format_types' => array('open', 'closed'),
410
        'description' => t('This fieldgroup renders the content in a fieldset, part of horizontal tabs group.'),
411
        'instance_settings' => array('description' => '', 'classes' => '', 'id' => ''),
412
        'default_formatter' => 'closed',
413
      ),
414
      'accordion' => array(
415
        'label' => t('Accordion group'),
416
        'description' => t('This fieldgroup renders child groups as jQuery accordion.'),
417
        'instance_settings' => array('description' => '', 'classes' => '', 'effect' => 'bounceslide'),
418
      ),
419
      'accordion-item' => array(
420
        'label' => t('Accordion item'),
421
        'format_types' => array('open', 'closed'),
422
        'description' => t('This fieldgroup renders the content in a div, part of accordion group.'),
423
        'instance_settings' => array('classes' => ''),
424
        'default_formatter' => 'closed',
425
      ),
426
    ),
427
  );
428
}
429

    
430
/**
431
 * Implements hook_field_group_format_settings().
432
 * If the group has no format settings, default ones will be added.
433
 * @params Object $group The group object.
434
 * @return Array $form The form element for the format settings.
435
 */
436
function field_group_field_group_format_settings($group) {
437
  // Add a wrapper for extra settings to use by others.
438
  $form = array(
439
    'instance_settings' => array(
440
      '#tree' => TRUE,
441
      '#weight' => 2,
442
    ),
443
  );
444

    
445
  $field_group_types = field_group_formatter_info();
446
  $mode = $group->mode == 'form' ? 'form' : 'display';
447
  $formatter = $field_group_types[$mode][$group->format_type];
448

    
449
  // Add the required formatter type selector.
450
  if (isset($formatter['format_types'])) {
451
    $form['formatter'] = array(
452
      '#title' => t('Fieldgroup settings'),
453
      '#type' => 'select',
454
      '#options' => drupal_map_assoc($formatter['format_types']),
455
      '#default_value' => isset($group->format_settings['formatter']) ? $group->format_settings['formatter'] : $formatter['default_formatter'],
456
      '#weight' => -4,
457
    );
458
  }
459

    
460
  if (isset($formatter['instance_settings']['required_fields']) && $mode == 'form') {
461
    $form['instance_settings']['required_fields'] = array(
462
      '#type' => 'checkbox',
463
      '#title' => t('Mark group as required if it contains required fields.'),
464
      '#default_value' => isset($group->format_settings['instance_settings']['required_fields']) ? $group->format_settings['instance_settings']['required_fields'] : (isset($formatter['instance_settings']['required_fields']) ? $formatter['instance_settings']['required_fields'] : ''),
465
      '#weight' => 2,
466
    );
467
  }
468

    
469
  if (isset($formatter['instance_settings']['id'])) {
470
    $form['instance_settings']['id'] = array(
471
      '#title' => t('ID'),
472
      '#type' => 'textfield',
473
      '#default_value' => isset($group->format_settings['instance_settings']['id']) ? $group->format_settings['instance_settings']['id'] : (isset($formatter['instance_settings']['id']) ? $formatter['instance_settings']['id'] : ''),
474
      '#weight' => 10,
475
      '#element_validate' => array('field_group_validate_id'),
476
    );
477
  }
478
  if (isset($formatter['instance_settings']['classes'])) {
479
    $form['instance_settings']['classes'] = array(
480
      '#title' => t('Extra CSS classes'),
481
      '#type' => 'textfield',
482
      '#default_value' => isset($group->format_settings['instance_settings']['classes']) ? $group->format_settings['instance_settings']['classes'] : (isset($formatter['instance_settings']['classes']) ? $formatter['instance_settings']['classes'] : ''),
483
      '#weight' => 11,
484
      '#element_validate' => array('field_group_validate_css_class'),
485
    );
486
  }
487

    
488
  if (isset($formatter['instance_settings']['description'])) {
489
    $form['instance_settings']['description'] = array(
490
      '#title' => t('Description'),
491
      '#type' => 'textarea',
492
      '#default_value' => isset($group->format_settings['instance_settings']['description']) ? $group->format_settings['instance_settings']['description'] : (isset($formatter['instance_settings']['description']) ? $formatter['instance_settings']['description'] : ''),
493
      '#weight' => 0,
494
    );
495
  }
496

    
497
  // Add optional instance_settings.
498
  switch ($group->format_type) {
499
    case 'html-element':
500
      $form['instance_settings']['element'] = array(
501
        '#title' => t('Element'),
502
        '#type' => 'textfield',
503
        '#default_value' => isset($group->format_settings['instance_settings']['element']) ? $group->format_settings['instance_settings']['element'] : $formatter['instance_settings']['element'],
504
        '#description' => t('E.g. div, section, aside etc.'),
505
        '#weight' => 1,
506
      );
507

    
508
      $form['instance_settings']['show_label'] = array(
509
        '#title' => t('Show label'),
510
        '#type' => 'select',
511
        '#options' => array(0 => t('No'), 1 => t('Yes')),
512
        '#default_value' => isset($group->format_settings['instance_settings']['show_label']) ? $group->format_settings['instance_settings']['show_label'] : $formatter['instance_settings']['show_label'],
513
        '#weight' => 2,
514
      );
515

    
516
      $form['instance_settings']['label_element'] = array(
517
        '#title' => t('Label element'),
518
        '#type' => 'textfield',
519
        '#default_value' => isset($group->format_settings['instance_settings']['label_element']) ? $group->format_settings['instance_settings']['label_element'] : $formatter['instance_settings']['label_element'],
520
        '#weight' => 3,
521
      );
522

    
523
      $form['instance_settings']['attributes'] = array(
524
        '#title' => t('Attributes'),
525
        '#type' => 'textfield',
526
        '#default_value' => isset($group->format_settings['instance_settings']['attributes']) ? $group->format_settings['instance_settings']['attributes'] : $formatter['instance_settings']['attributes'],
527
        '#description' => t('E.g. name="anchor"'),
528
        '#weight' => 4,
529
      );
530
      break;
531
    case 'div':
532
      $form['label']['#description'] = t('Please enter a label for collapsible elements');
533
      $form['instance_settings']['show_label'] = array(
534
        '#title' => t('Show label'),
535
        '#type' => 'select',
536
        '#options' => array(0 => t('No'), 1 => t('Yes')),
537
        '#default_value' => isset($group->format_settings['instance_settings']['show_label']) ? $group->format_settings['instance_settings']['show_label'] : $formatter['instance_settings']['show_label'],
538
        '#weight' => 2,
539
      );
540
      $form['instance_settings']['label_element'] = array(
541
        '#title' => t('Label element'),
542
        '#type' => 'select',
543
        '#options' => array('h2' => t('Header 2'), 'h3' => t('Header 3')),
544
        '#default_value' => isset($group->format_settings['instance_settings']['label_element']) ? $group->format_settings['instance_settings']['label_element'] : $formatter['instance_settings']['label_element'],
545
        '#weight' => 2,
546
      );
547
      $form['instance_settings']['effect'] = array(
548
        '#title' => t('Effect'),
549
        '#type' => 'select',
550
        '#options' => array('none' => t('None'), 'blind' => t('Blind')),
551
        '#default_value' => isset($group->format_settings['instance_settings']['effect']) ? $group->format_settings['instance_settings']['effect'] : $formatter['instance_settings']['effect'],
552
        '#weight' => 3,
553
      );
554
      $form['instance_settings']['speed'] = array(
555
        '#title' => t('Speed'),
556
        '#type' => 'select',
557
        '#options' => array('none' => t('None'), 'slow' => t('Slow'), 'fast' => t('Fast')),
558
        '#default_value' => isset($group->format_settings['instance_settings']['speed']) ? $group->format_settings['instance_settings']['speed'] : $formatter['instance_settings']['speed'],
559
        '#weight' => 3,
560
      );
561
      break;
562
    case 'html5':
563
      $form['instance_settings']['wrapper'] = array(
564
        '#title' => t('HTML5 wrapper'),
565
        '#type' => 'select',
566
        '#options' => array('section' => t('Section'), 'article' => t('Article'), 'header' => t('Header'), 'footer' => t('Footer'), 'aside' => t('Aside')),
567
        '#default_value' => isset($group->format_settings['instance_settings']['wrapper']) ? $group->format_settings['instance_settings']['wrapper'] : 'section',
568
      );
569
      break;
570
    case 'fieldset':
571
      $form['label']['#description'] = t('Please enter a label for collapsible elements');
572
      break;
573
    case 'multipage-group':
574
      $form['instance_settings']['page_header'] = array(
575
        '#title' => t('Format page title'),
576
        '#type' => 'select',
577
        '#options' => array(0 => t('None'), 1 => t('Label only'), 2 => t('Step 1 of 10'), 3 => t('Step 1 of 10 [Label]'),),
578
        '#default_value' => isset($group->format_settings['instance_settings']['page_header']) ? $group->format_settings['instance_settings']['page_header'] : $formatter['instance_settings']['page_header'],
579
        '#weight' => 1,
580
      );
581
      $form['instance_settings']['page_counter'] = array(
582
        '#title' => t('Add a page counter at the bottom'),
583
        '#type' => 'select',
584
        '#options' => array(0 => t('No'), 1 => t('Format 1 / 10'), 2 => t('The count number only')),
585
        '#default_value' => isset($group->format_settings['instance_settings']['page_counter']) ? $group->format_settings['instance_settings']['page_counter'] : $formatter['instance_settings']['page_counter'],
586
        '#weight' => 2,
587
      );
588
      $form['instance_settings']['move_button'] = array(
589
        '#title' => t('Move submit button to last multipage'),
590
        '#type' => 'select',
591
        '#options' => array(0 => t('No'), 1 => t('Yes')),
592
        '#default_value' => isset($group->format_settings['instance_settings']['move_button']) ? $group->format_settings['instance_settings']['move_button'] : $formatter['instance_settings']['move_button'],
593
        '#weight' => 3,
594
      );
595
      $form['instance_settings']['move_additional'] = array(
596
        '#title' => t('Move additional settings to last multipage (if available)'),
597
        '#type' => 'select',
598
        '#options' => array(0 => t('No'), 1 => t('Yes')),
599
        '#default_value' => isset($group->format_settings['instance_settings']['move_additional']) ? $group->format_settings['instance_settings']['move_additional'] : $formatter['instance_settings']['move_additional'],
600
        '#weight' => 4,
601
      );
602
    case 'tabs':
603
    case 'htabs':
604
      break;
605
    case 'accordion':
606
      $form['instance_settings']['effect'] = array(
607
        '#title' => t('Effect'),
608
        '#type' => 'select',
609
        '#options' => array('none' => t('None'), 'bounceslide' => t('Bounce slide')),
610
        '#default_value' => isset($group->format_settings['instance_settings']['effect']) ? $group->format_settings['instance_settings']['effect'] : $formatter['instance_settings']['effect'],
611
        '#weight' => 2,
612
      );
613
      break;
614
    case 'multipage':
615
      break;
616
    case 'tab':
617
    case 'htab':
618
    case 'accordion-item':
619
    default:
620
  }
621

    
622
  return $form;
623
}
624

    
625
/**
626
 * Helper function to prepare basic variables needed for most formatters.
627
 *
628
 * Called in field_group_field_group_pre_render(), but can also be called in
629
 * other implementations of hook_field_group_pre_render().
630
 */
631
function field_group_pre_render_prepare(&$group) {
632

    
633
  $classes = _field_group_get_html_classes($group);
634

    
635
  $group->classes = implode(' ', $classes->required);
636
  $group->description = !empty($group->format_settings['instance_settings']['description']) ? filter_xss_admin(t($group->format_settings['instance_settings']['description'])) : '';
637

    
638
}
639

    
640
/**
641
 * Implements hook_field_group_pre_render().
642
 *
643
 * @param Array $elements by address.
644
 * @param Object $group The Field group info.
645
 */
646
function field_group_field_group_pre_render(&$element, &$group, & $form) {
647

    
648
  field_group_pre_render_prepare($group);
649

    
650
  $view_mode = isset($form['#view_mode']) ? $form['#view_mode'] : 'form';
651

    
652
  // Add all field_group format types to the js settings.
653
  $form['#attached']['js'][] = array(
654
    'data' => array('field_group' => array($group->format_type => $view_mode)),
655
    'type' => 'setting',
656
  );
657

    
658
  if (isset($group->format_settings['instance_settings']['id']) && !empty($group->format_settings['instance_settings']['id'])) {
659
    $element['#id'] = drupal_html_id($group->format_settings['instance_settings']['id']);
660
  }
661

    
662
  $element['#weight'] = $group->weight;
663

    
664
  // Call the pre render function for the format type.
665
  $function = "field_group_pre_render_" . str_replace("-", "_", $group->format_type);
666
  if (function_exists($function)) {
667
    $function($element, $group, $form);
668
  }
669

    
670
}
671

    
672
/**
673
 * Implements field_group_pre_render_<format-type>.
674
 * Format type: Fieldset.
675
 *
676
 * @param $element The field group form element.
677
 * @param $group The Field group object prepared for pre_render.
678
 * @param $form The root element or form.
679
 */
680
function field_group_pre_render_fieldset(&$element, $group, &$form) {
681

    
682
  $element += array(
683
    '#type' => 'fieldset',
684
    '#title' => check_plain(t($group->label)),
685
    '#collapsible' => $group->collapsible,
686
    '#collapsed' => $group->collapsed,
687
    '#pre_render' => array(),
688
    '#attributes' => array('class' => explode(' ', $group->classes)),
689
    '#description' => $group->description,
690
  );
691

    
692
  if ($group->collapsible || $group->collapsed) {
693
    $element['#attached']['library'][] = array('system', 'drupal.collapse');
694
  }
695
}
696

    
697
/**
698
 * Implements field_group_pre_render_<format-type>.
699
 * Format type: HTML element.
700
 *
701
 * @param $element The field group form element.
702
 * @param $group The Field group object prepared for pre_render.
703
 * @param $form The root element or form.
704
 */
705
function field_group_pre_render_html_element(&$element, $group, &$form) {
706
  $html_element = isset($group->format_settings['instance_settings']['element']) ? $group->format_settings['instance_settings']['element'] : 'div';
707
  $show_label = isset($group->format_settings['instance_settings']['show_label']) ? $group->format_settings['instance_settings']['show_label'] : 0;
708
  $label_element = isset($group->format_settings['instance_settings']['label_element']) ? $group->format_settings['instance_settings']['label_element'] : 'div';
709
  $attributes = isset($group->format_settings['instance_settings']['attributes']) ? ' ' . $group->format_settings['instance_settings']['attributes'] : '';
710
  $group->classes = trim($group->classes);
711

    
712
  // This regex split the attributes string so that we can pass that
713
  // later to drupal_attributes().
714
  preg_match_all('/([^\s=]+)="([^"]+)"/', $attributes, $matches);
715

    
716
  $element_attributes = array();
717
  // Put the attribute and the value together.
718
  foreach ($matches[1] as $key => $attribute) {
719
    $element_attributes[$attribute] = $matches[2][$key];
720
  }
721

    
722
  // Add the classes to the attributes array.
723
  if (!isset($element_attributes['class']) && $group->classes) {
724
    $element_attributes['class'] = $group->classes;
725
  }
726
  elseif (isset($element_attributes['class']) && $group->classes) {
727
    $element_attributes['class'] .= ' ' . $group->classes;
728
  }
729

    
730
  $attributes = drupal_attributes($element_attributes);
731

    
732
  $element['#prefix'] = '<' . $html_element . $attributes . '>';
733
  if ($show_label) {
734
    $element['#prefix'] .= '<' . $label_element . '><span>' . check_plain(t($group->label)) . '</span></' . $label_element . '>';
735
  }
736
  $element['#suffix'] = '</' . $html_element . '>';
737
}
738

    
739
/**
740
 * Implements field_group_pre_render_<format-type>.
741
 * Format type: Div.
742
 *
743
 * @param $element The field group form element.
744
 * @param $group The Field group object prepared for pre_render.
745
 * @param $form The root element or form.
746
 */
747
function field_group_pre_render_div(&$element, $group, &$form) {
748

    
749
  $show_label = isset($group->format_settings['instance_settings']['show_label']) ? $group->format_settings['instance_settings']['show_label'] : 0;
750
  $label_element = isset($group->format_settings['instance_settings']['label_element']) ? $group->format_settings['instance_settings']['label_element'] : 'h2';
751
  $effect = isset($group->format_settings['instance_settings']['effect']) ? $group->format_settings['instance_settings']['effect'] : 'none';
752

    
753
  $element['#type'] = 'markup';
754
  $id = isset($element['#id']) ? ' id="' . $element['#id'] . '"' : '';
755

    
756
  if ($group->format_settings['formatter'] != 'open') {
757

    
758
    $element['#prefix'] = '<div' . $id . ' class="' . $group->classes . '">
759
      <' . $label_element . '><span class="field-group-format-toggler">' . check_plain(t($group->label)) . '</span></' . $label_element . '>
760
      <div class="field-group-format-wrapper" style="display: ' . (!empty($group->collapsed) ? 'none' : 'block') . ';">';
761
    $element['#suffix'] = '</div></div>';
762
  }
763
  else {
764
    $class_attribute = !empty($group->classes) ? ' class="' . $group->classes . '"' : '';
765

    
766
    $element['#prefix'] = '<div' . $id . $class_attribute . '>';
767
    if ($show_label) {
768
      $element['#prefix'] .= '<' . $label_element . '><span>' . check_plain(t($group->label)) . '</span></' . $label_element . '>';
769
    }
770
    $element['#suffix'] = '</div>';
771
  }
772
  if (!empty($group->description)) {
773
    $element['#prefix'] .= '<div class="description">' . $group->description . '</div>';
774
  }
775

    
776
  if ($effect == 'blind') {
777
    $element['#attached']['library'][] = array('system', 'effects.blind');
778
  }
779

    
780
}
781

    
782
/**
783
 * Implements field_group_pre_render_<format-type>.
784
 * Format type: HTML5.
785
 *
786
 * @param $element The field group form element.
787
 * @param $group The Field group object prepared for pre_render.
788
 * @param $form The root element or form.
789
 */
790
function field_group_pre_render_html5(&$element, $group, &$form) {
791
  $id = !empty($element['#id']) ? ' id="' . $element['#id'] . '"' : '';
792
  $class = !empty($group->classes) ? ' class="' . $group->classes . '"' : '';
793
  $element += array(
794
    '#type' => 'markup',
795
    '#prefix' => '<' . $group->format_settings['instance_settings']['wrapper'] . $id . $class . '>',
796
    '#suffix' => '</' . $group->format_settings['instance_settings']['wrapper'] . '>',
797
  );
798
}
799

    
800
/**
801
 * Implements field_group_pre_render_<format-type>.
802
 * Format type: Accordion.
803
 *
804
 * @param $element The field group form element.
805
 * @param $group The Field group object prepared for pre_render.
806
 * @param $form The root element or form.
807
 */
808
function field_group_pre_render_accordion(&$element, $group, &$form) {
809

    
810
  // Add the jQuery UI accordion.
811
  $element['#attached']['library'][] = array('system', 'ui.accordion');
812

    
813
  $element += array(
814
    '#type' => 'markup',
815
    '#prefix' => '<div class="' . $group->classes . '">',
816
    '#suffix' => '</div>',
817
  );
818
}
819

    
820
/**
821
 * Implements field_group_pre_render_<format-type>.
822
 * Format type: Accordion item.
823
 *
824
 * @param $element The field group form element.
825
 * @param $group The Field group object prepared for pre_render.
826
 * @param $form The root element or form.
827
 */
828
function field_group_pre_render_accordion_item(&$element, $group, &$form) {
829

    
830
  $element += array(
831
    '#type' => 'markup',
832
    '#prefix' => '<h3 class="field-group-format-toggler ' . $group->format_type . ($group->collapsed ? '' : ' field-group-accordion-active') . '"><a href="#">' . check_plain(t($group->label)) . '</a></h3>
833
    <div class="field-group-format-wrapper ' . $group->classes . '">',
834
    '#suffix' => '</div>',
835
    //'#attributes' => array('class' => array($group->format_type)),
836
  );
837
  if (!empty($group->description)) {
838
    $element['#prefix'] .= '<div class="description">' . $group->description . '</div>';
839
  }
840

    
841
}
842

    
843
/**
844
 * Implements field_group_pre_render_<format-type>.
845
 * Format type: Horizontal tabs group.
846
 *
847
 * @param $element The field group form element.
848
 * @param $group The Field group object prepared for pre_render.
849
 * @param $form The root element or form.
850
 */
851
function field_group_pre_render_htabs(&$element, $group, &$form) {
852

    
853
  $element += array(
854
    '#type' => 'horizontal_tabs',
855
    '#title' => check_plain(t($group->label)),
856
    '#theme_wrappers' => array('horizontal_tabs'),
857
    '#prefix' => '<div class="field-group-' . $group->format_type . '-wrapper ' . $group->classes . '">',
858
    '#suffix' => '</div>',
859
  );
860

    
861
  // By default vertical_tabs don't have titles but you can override it in the theme.
862
  if (!empty($group->label)) {
863
    $element['#title'] = check_plain($group->label);
864
  }
865

    
866
  // Only add form.js on forms.
867
  if (!empty($form['#type']) && $form['#type'] == 'form') {
868
    $element['#attached']['js'][] = 'misc/form.js';
869
  }
870

    
871
  $element['#attached']['library'][] = array('field_group', 'horizontal-tabs');
872
}
873

    
874
/**
875
 * Implements field_group_pre_render_<format-type>.
876
 * Format type: Horizontal tab.
877
 *
878
 * @param $element The field group form element.
879
 * @param $group The Field group object prepared for pre_render.
880
 * @param $form The root element or form.
881
 */
882
function field_group_pre_render_htab(&$element, $group, &$form) {
883

    
884
  $element += array(
885
    '#type' => 'fieldset',
886
    '#title' => check_plain(t($group->label)),
887
    '#collapsible' => $group->collapsible,
888
    '#collapsed' => $group->collapsed,
889
    '#attributes' => array('class' => explode(" ", $group->classes)),
890
    '#group' => $group->parent_name,
891
    // very important. Cannot be added on the form!
892
    '#parents' => array($group->parent_name),
893
    '#description' => $group->description,
894
  );
895

    
896
}
897

    
898
/**
899
 * Implements field_group_pre_render_<format-type>.
900
 * Format type: Multipage group.
901
 *
902
 * @param $element The field group form element.
903
 * @param $group The Field group object prepared for pre_render.
904
 * @param $form The root element or form.
905
 */
906
function field_group_pre_render_multipage_group(&$element, &$group, &$form) {
907

    
908
  $multipage_element = array(
909
    '#type' => 'multipage',
910
    '#theme_wrappers' => array('multipage'),
911
    '#prefix' => '<div class="field-group-' . $group->format_type . '-wrapper ' . $group->classes . '">',
912
    '#suffix' => '</div>',
913
  );
914

    
915
  $element += $multipage_element;
916

    
917
  $move_additional = isset($group->format_settings['instance_settings']['move_additional']) ? ($group->format_settings['instance_settings']['move_additional'] && isset($form['additional_settings'])) : isset($form['additional_settings']);
918
  $move_button = isset($group->format_settings['instance_settings']['move_button']) ? $group->format_settings['instance_settings']['move_button'] : 0;
919

    
920
  drupal_add_js(array(
921
    'field_group' => array(
922
      'multipage_move_submit' => (bool) $move_button,
923
      'multipage_move_additional' => (bool) $move_additional
924
    )
925
  ), 'setting');
926

    
927
}
928

    
929
/**
930
 * Implements field_group_pre_render_<format-type>.
931
 * Format type: Multipage.
932
 *
933
 * @param $element The field group form element.
934
 * @param $group The Field group object prepared for pre_render.
935
 * @param $form The root element or form.
936
 */
937
function field_group_pre_render_multipage(&$element, $group, &$form) {
938

    
939
  $group->classes .= $group->format_settings['formatter'] == 'start' ? ' multipage-open' : ' multipage-closed';
940
  $element += array(
941
    '#type' => 'multipage_pane',
942
    '#title' => check_plain(t($group->label)),
943
    '#collapsible' => $group->collapsible,
944
    '#collapsed' => $group->collapsed,
945
    '#attributes' => array('class' => explode(" ", $group->classes)),
946
    '#group' => $group->parent_name,
947
    '#group_object' => $group,
948
    '#parent_group_object' => $form['#groups'][$group->parent_name],
949
    // very important. Cannot be added on the form!
950
    '#parents' => array($group->parent_name),
951
    '#description' => $group->description,
952
  );
953

    
954
  $element['#attached']['library'][] = array('field_group', 'multipage');
955
}
956

    
957
/**
958
 * Implements field_group_pre_render_<format-type>.
959
 * Format type: Vertical tabs wrapper.
960
 *
961
 * @param $element The field group form element.
962
 * @param $group The Field group object prepared for pre_render.
963
 * @param $form The root element or form.
964
 */
965
function field_group_pre_render_tabs(&$element, $group, &$form) {
966

    
967
  $element += array(
968
    '#type' => 'vertical_tabs',
969
    '#theme_wrappers' => array('vertical_tabs'),
970
    '#prefix' => '<div class="field-group-' . $group->format_type . '-wrapper ' . $group->classes . '">',
971
    '#suffix' => '</div>',
972
  );
973

    
974
  // By default vertical_tabs don't have titles but you can override it in the theme.
975
  if (!empty($group->label)) {
976
    $element['#title'] = check_plain($group->label);
977
  }
978

    
979
  $element[$group->group_name . '__active_tab'] = array(
980
    '#type' => 'hidden',
981
    '#default_value' => '',
982
    '#attributes' => array('class' => array('vertical-tabs-active-tab')),
983
  );
984

    
985
  $element['#attached']['library'][] = array('system', 'drupal.collapse');
986
}
987

    
988
/**
989
 * Implements field_group_pre_render_<format-type>.
990
 * Format type: Vertical tab.
991
 *
992
 * @param $element The field group form element.
993
 * @param $group The Field group object prepared for pre_render.
994
 * @param $form The root element or form.
995
 */
996
function field_group_pre_render_tab(&$element, $group, &$form) {
997

    
998
  $view_mode = isset($form['#view_mode']) ? $form['#view_mode'] : 'form';
999

    
1000
  // Could be it never runs through htab.
1001
  $form['#attached']['js'][] = array(
1002
    'data' => array('field_group' => array('tabs' => $view_mode)),
1003
    'type' => 'setting',
1004
  );
1005

    
1006
  $add = array(
1007
    '#type' => 'fieldset',
1008
    '#id' => 'edit-' . $group->group_name,
1009
    '#title' => check_plain(t($group->label)),
1010
    '#collapsible' => $group->collapsible,
1011
    '#collapsed' => $group->collapsed,
1012
    '#attributes' => array('class' => explode(" ", $group->classes)),
1013
    '#description' => $group->description,
1014
  );
1015

    
1016
  // Front-end and back-end on configuration will lead
1017
  // to vertical tabs nested in a separate vertical group.
1018
  if ($view_mode != 'form') {
1019
    $add['#group'] = empty($group->parent_name) ? 'additional_settings' : $group->parent_name;
1020
    $add['#parents'] = array($add['#group']);
1021
    $element += $add;
1022
  }
1023
  // Form fieldgroups which are nested into a vertical tab group
1024
  // are handled a little different.
1025
  elseif (!empty($group->parent_name)) {
1026
    $add['#group'] = $group->parent_name;
1027
    $element += $add;
1028
  }
1029
  // Forms "can" have additional settins. We'll try to locate it first, if not
1030
  // exists, field_group will create a parallel additional settings entry.
1031
  else {
1032
    // Create the fieldgroup element.
1033
    $add['#parents'] = array('additional_settings');
1034
    $add['#group'] = 'additional_settings';
1035
    $add['#weight'] = -30 + $group->weight; // hardcoded to bring our extra additional vtabs on top.
1036

    
1037
    // Check if the additional_settings exist for this type of form.
1038
    if (isset($form['additional_settings']['group']['#groups']['additional_settings'])) {
1039

    
1040
      // Merge fieldgroups with the core additional settings.
1041
      $form['additional_settings']['group']['#groups']['additional_settings'][$group->group_name] = $add;
1042
      $form['additional_settings']['group']['#groups'][$group->group_name] = array('#group_exists' => TRUE);
1043
      // Nest the fields inside the appropriate structure.
1044
      foreach (element_children($element) as $fieldname) {
1045
        $form['additional_settings']['group']['#groups']['additional_settings'][$group->group_name][$fieldname] = &$element[$fieldname];
1046
        unset($element[$fieldname]);
1047
      }
1048
    }
1049
    // Assumption the wrapper is in the root. This could be done by field_group itself
1050
    // in previous loop of tabs in same wrapper or even some other contrib / custom module.
1051
    else {
1052
      if (!isset($form['additional_settings']['#type'])) {
1053
        $form['additional_settings'] = array(
1054
          '#type' => 'vertical_tabs',
1055
          '#weight' => $group->weight,
1056
          '#theme_wrappers' => array('vertical_tabs'),
1057
          '#prefix' => '<div class="field-group-' . $group->format_type . '-wrapper">',
1058
          '#suffix' => '</div>',
1059
        );
1060
        $form['#attached']['library'][] = array('system', 'drupal.collapse');
1061
      }
1062
      $form['additional_settings'][$group->group_name] = $add;
1063
      // Nest the fields inside the appropriate structure.
1064
      foreach (element_children($element) as $fieldname) {
1065
        $form['additional_settings'][$group->group_name][$fieldname] = &$element[$fieldname];
1066
        unset($element[$fieldname]);
1067
      }
1068
    }
1069
  }
1070

    
1071
}
1072

    
1073
/**
1074
 * Implements hook_field_group_build_pre_render_alter().
1075
 * @param Array $elements by address.
1076
 */
1077
function field_group_field_group_build_pre_render_alter(& $element) {
1078

    
1079
  // Someone is doing a node view, in a node view. Reset content.
1080
  // TODO Check if this breaks something else.
1081
  if (isset($element['#node']->content) && count($element['#node']->content) > 0) {
1082
    $element['#node']->content = array();
1083
  }
1084

    
1085
  $display = isset($element['#view_mode']);
1086
  $groups = array_keys($element['#groups']);
1087

    
1088
  // Dish the fieldgroups with no fields for non-forms.
1089
  if ($display) {
1090
    field_group_remove_empty_display_groups($element, $groups);
1091
  }
1092
  else {
1093
    // Fix the problem on forms with additional settings.
1094
    field_group_remove_empty_form_groups('form', $element, $groups, $element['#groups'], $element['#entity_type']);
1095
  }
1096

    
1097
  // Add the default field_group javascript and stylesheet.
1098
  $element['#attached']['js'][] = drupal_get_path('module', 'field_group') . '/field_group.js';
1099
  $element['#attached']['css'][] = drupal_get_path('module', 'field_group') . '/field_group.css';
1100

    
1101
  // Move additional settings to the last multipage pane if configured that way.
1102
  // Note that multipages MUST be in the root of the form.
1103
  foreach (element_children($element) as $name) {
1104
    if (isset($element[$name]['#type']) && $element[$name]['#type'] == 'multipage' && isset($element['additional_settings'])) {
1105
      $parent_group = $element['#groups'][$name];
1106
      $move_additional = isset($parent_group->format_settings['instance_settings']['move_additional']) ? $parent_group->format_settings['instance_settings']['move_additional'] : 1;
1107
      $last_pane = NULL;
1108
      foreach (element_children($element[$name], TRUE) as $pane) {
1109
        $last_pane = $pane;
1110
      }
1111
      $element[$name][$last_pane]['additional_settings'] = $element['additional_settings'];
1112
      unset($element['additional_settings']);
1113
    }
1114
  }
1115

    
1116
}
1117

    
1118
/**
1119
 * Remove empty groups on forms.
1120
 *
1121
 * @param String $parent_name
1122
 *   The name of the element.
1123
 * @param array $element
1124
 *   The element to check the empty state.
1125
 * @param array $groups
1126
 *   Array of group objects.
1127
 */
1128
function field_group_remove_empty_form_groups($name, & $element, $groups, &$form_groups, $entity) {
1129

    
1130
  $exceptions = array('user__account', 'comment__author');
1131

    
1132
  $children = element_children($element);
1133

    
1134
  $hasChildren = FALSE;
1135
  if (count($children)) {
1136
    foreach ($children as $childname) {
1137

    
1138
      if (in_array($childname, $groups)) {
1139
        field_group_remove_empty_form_groups($childname, $element[$childname], $groups, $form_groups, $entity);
1140
      }
1141
      $exception = $entity . '__' . $childname;
1142
      $hasChildren = $hasChildren ? TRUE : (isset($element[$childname]['#type']) || isset($element[$childname]['#markup']) || in_array($exception, $exceptions));
1143

    
1144
    }
1145
  }
1146

    
1147
  if (!$hasChildren) {
1148

    
1149
    // Remove empty elements from the #groups.
1150
    if (empty($element) && isset($form_groups[$name]) && !is_array($form_groups[$name])) {
1151
      foreach ($form_groups as $group_name => $group) {
1152
        if (isset($group->children)) {
1153
          $group_children = array_flip($group->children);
1154
          if (isset($group_children[$name])) {
1155
            unset($form_groups[$group_name]->children[$group_children[$name]]);
1156
          }
1157
        }
1158
      }
1159
    }
1160

    
1161
    $element['#access'] = FALSE;
1162

    
1163
  }
1164

    
1165
}
1166

    
1167
/**
1168
 * Remove empty groups on entity display.
1169
 * @param array $element
1170
 *   The element to check the empty state.
1171
 * @param array $groups
1172
 *   Array of group objects.
1173
 */
1174
function field_group_remove_empty_display_groups(& $element, $groups) {
1175

    
1176
  $empty_child = TRUE;
1177
  $empty_group = TRUE;
1178

    
1179
  // Loop through the children for current element.
1180
  foreach (element_children($element) as $name) {
1181

    
1182
    // Descend if the child is a group.
1183
    if (in_array($name, $groups)) {
1184
      $empty_child = field_group_remove_empty_display_groups($element[$name], $groups);
1185
      if (!$empty_child) {
1186
        $empty_group = FALSE;
1187
      }
1188
    }
1189
    // Child is a field, the element is not empty and access is set to true (or empty).
1190
    elseif (!empty($element[$name]) && (!isset($element[$name]['#access']) || $element[$name]['#access'])) {
1191
      $empty_group = FALSE;
1192
    }
1193

    
1194
  }
1195

    
1196
  // Reset an empty group.
1197
  if ($empty_group) {
1198
    $element = NULL;
1199
  }
1200

    
1201
  return $empty_group;
1202

    
1203
}
1204

    
1205
/**
1206
 * Implements hook_field_group_format_summary().
1207
 */
1208
function field_group_field_group_format_summary($group) {
1209

    
1210
  $group_form = module_invoke_all('field_group_format_settings', $group);
1211

    
1212
  $output = '';
1213
  if (isset($group->format_settings['formatter'])) {
1214
    $output .= '<strong>' . $group->format_type . '</strong> ' . $group->format_settings['formatter'] . '';
1215
  }
1216
  if (isset($group->format_settings['instance_settings'])) {
1217
    $last = end($group->format_settings['instance_settings']);
1218
    $output .= '<br />';
1219
    foreach ($group->format_settings['instance_settings'] as $key => $value) {
1220
      if (empty($value)) {
1221
        continue;
1222
      }
1223

    
1224
      $output .= '<strong>' . $key . '</strong> ';
1225

    
1226
      if (isset($group_form['instance_settings'], $group_form['instance_settings'][$key]['#options'])) {
1227
        if (is_array($value)) {
1228
          $value = implode(array_filter($value), ', ');
1229
        }
1230
        else {
1231
          $value = $group_form['instance_settings'][$key]['#options'][$value];
1232
        }
1233
      }
1234

    
1235
      // Shorten the string.
1236
      if (drupal_strlen($value) > 38) {
1237
        $value = truncate_utf8($value, 50, TRUE, TRUE);
1238
      }
1239
      // If still numeric, handle it as yes or no.
1240
      elseif (is_numeric($value)) {
1241
        $value = $value == '1' ? t('yes') : t('no');
1242
      }
1243
      $output .= check_plain($value);
1244
      $output .= $last == $value ? ' ' : '<br />';
1245
    }
1246
  }
1247
  return $output;
1248
}
1249

    
1250
/**
1251
 * Implements hook_element_info().
1252
 */
1253
function field_group_element_info() {
1254
  $types['horizontal_tabs'] = array(
1255
    '#theme_wrappers' => array('horizontal_tabs'),
1256
    '#default_tab' => '',
1257
    '#process' => array('form_process_horizontal_tabs'),
1258
  );
1259
  $types['multipage'] = array(
1260
    '#theme_wrappers' => array('multipage'),
1261
    '#default_tab' => '',
1262
    '#process' => array('form_process_multipage'),
1263
  );
1264
  $types['multipage_pane'] = array(
1265
    '#value' => NULL,
1266
    '#process' => array('form_process_fieldset', 'ajax_process_form'),
1267
    '#pre_render' => array('form_pre_render_fieldset'),
1268
    '#theme_wrappers' => array('multipage_pane'),
1269
  );
1270
  return $types;
1271
}
1272

    
1273
/**
1274
 * Implements hook_library().
1275
 */
1276
function field_group_library() {
1277

    
1278
  $path = drupal_get_path('module', 'field_group');
1279
  // Horizontal Tabs.
1280
  $libraries['horizontal-tabs'] = array(
1281
    'title' => 'Horizontal Tabs',
1282
    'website' => 'http://drupal.org/node/323112',
1283
    'version' => '1.0',
1284
    'js' => array(
1285
      $path . '/horizontal-tabs/horizontal-tabs.js' => array(),
1286
    ),
1287
    'css' => array(
1288
      $path . '/horizontal-tabs/horizontal-tabs.css' => array(),
1289
    ),
1290
  );
1291
  // Multipage Tabs.
1292
  $libraries['multipage'] = array(
1293
    'title' => 'Multipage',
1294
    'website' => 'http://drupal.org/node/323112',
1295
    'version' => '1.0',
1296
    'js' => array(
1297
      $path . '/multipage/multipage.js' => array(),
1298
    ),
1299
    'css' => array(
1300
      $path . '/multipage/multipage.css' => array(),
1301
    ),
1302
  );
1303

    
1304
  return $libraries;
1305
}
1306

    
1307
/**
1308
 * Implements hook_field_extra_fields().
1309
 */
1310
function field_group_field_extra_fields() {
1311
  $extra = array();
1312

    
1313
  $extra['user']['user'] = array('form' => array());
1314

    
1315
  // User picture field to integrate with user module.
1316
  if (variable_get('user_pictures', 0)) {
1317
    $extra['user']['user']['form']['picture'] = array(
1318
      'label' => t('Picture'),
1319
      'description' => t('User picture'),
1320
      'weight' => 5,
1321
    );
1322
  }
1323

    
1324
  // Field to itegrate with overlay module.
1325
  if (module_exists('overlay')) {
1326
    $extra['user']['user']['form']['overlay_control'] = array(
1327
      'label' => t('Administrative overlay'),
1328
      'description' => t('Administrative overlay'),
1329
      'weight' => 5,
1330
    );
1331
  }
1332

    
1333
  // Field to itegrate with contact module.
1334
  if (module_exists('contact')) {
1335
    $extra['user']['user']['form']['contact'] = array(
1336
      'label' => t('Contact'),
1337
      'description' => t('Contact user element'),
1338
     'weight' => 5,
1339
    );
1340
  }
1341

    
1342
  // Field to integrate with the locale module.
1343
  if (module_exists('locale')) {
1344
    $extra['user']['user']['form']['locale'] = array(
1345
      'label' => t('Language settings'),
1346
      'description' => t('Language settings for the user account.'),
1347
      'weight' => 5,
1348
    );
1349
  }
1350

    
1351
  // Field to integrate with the wysiwyg module on user settings.
1352
  if (module_exists('wysiwyg')) {
1353
    $extra['user']['user']['form']['wysiwyg'] = array(
1354
      'label' => t('Wysiwyg status'),
1355
      'description' => t('Text formats enabled for rich-text editing'),
1356
      'weight' => 5,
1357
    );
1358
  }
1359

    
1360
  return $extra;
1361
}
1362

    
1363
/**
1364
 * Implements hook_field_attach_rename_bundle().
1365
 */
1366
function field_group_field_attach_rename_bundle($entity_type, $bundle_old, $bundle_new) {
1367
  db_query('UPDATE {field_group} SET bundle = :bundle WHERE bundle = :old_bundle AND entity_type = :entity_type', array(
1368
    ':bundle' => $bundle_new,
1369
    ':old_bundle' => $bundle_old,
1370
    ':entity_type' => $entity_type,
1371
  ));
1372
}
1373

    
1374
/**
1375
 * Creates a group formatted as horizontal tabs.
1376
 * This function will never be callable from within field_group rendering. Other
1377
 * modules using #type horizontal_tabs will have the benefit of this processor.
1378
 *
1379
 * @param $element
1380
 *   An associative array containing the properties and children of the
1381
 *   fieldset.
1382
 * @param $form_state
1383
 *   The $form_state array for the form this horizontal tab widget belongs to.
1384
 * @return
1385
 *   The processed element.
1386
 */
1387
function form_process_horizontal_tabs($element, &$form_state) {
1388
  // Inject a new fieldset as child, so that form_process_fieldset() processes
1389
  // this fieldset like any other fieldset.
1390
  $element['group'] = array(
1391
    '#type' => 'fieldset',
1392
    '#theme_wrappers' => array(),
1393
    '#parents' => $element['#parents'],
1394
  );
1395

    
1396
  // The JavaScript stores the currently selected tab in this hidden
1397
  // field so that the active tab can be restored the next time the
1398
  // form is rendered, e.g. on preview pages or when form validation
1399
  // fails.
1400
  $name = implode('__', $element['#parents']);
1401
  if (isset($form_state['values'][$name . '__active_tab'])) {
1402
    $element['#default_tab'] = $form_state['values'][$name . '__active_tab'];
1403
  }
1404
  $element[$name . '__active_tab'] = array(
1405
    '#type' => 'hidden',
1406
    '#default_value' => $element['#default_tab'],
1407
    '#attributes' => array('class' => array('horizontal-tabs-active-tab')),
1408
  );
1409

    
1410
  return $element;
1411
}
1412

    
1413
/**
1414
 * Returns HTML for an element's children fieldsets as horizontal tabs.
1415
 *
1416
 * @param $variables
1417
 *   An associative array containing:
1418
 *   - element: An associative array containing the properties and children of the
1419
 *     fieldset. Properties used: #children.
1420
 *
1421
 * @ingroup themeable
1422
 */
1423
function theme_horizontal_tabs($variables) {
1424
  $element = $variables['element'];
1425
  // Add required JavaScript and Stylesheet.
1426
  $element['#attached']['library'][] = array('field_group', 'horizontal-tabs');
1427

    
1428
  $output = '<h2 class="element-invisible">' . (!empty($element['#title']) ? $element['#title'] : t('Horizontal Tabs')) . '</h2>';
1429
  $output .= '<div class="horizontal-tabs-panes">' . $element['#children'] . '</div>';
1430

    
1431
  return $output;
1432
}
1433

    
1434
/**
1435
 * Creates a group formatted as multipage.
1436
 * This function will never be callable from within field_group rendering. Other
1437
 * modules using #type multipage will have the benefit of this processor.
1438
 *
1439
 * @param $element
1440
 *   An associative array containing the properties and children of the
1441
 *   fieldset.
1442
 * @param $form_state
1443
 *   The $form_state array for the form this multipage tab widget belongs to.
1444
 * @return
1445
 *   The processed element.
1446
 */
1447
function form_process_multipage($element, &$form_state) {
1448
  // Inject a new fieldset as child, so that form_process_fieldset() processes
1449
  // this fieldset like any other fieldset.
1450
  $element['group'] = array(
1451
    '#type' => 'fieldset',
1452
    '#theme_wrappers' => array(),
1453
    '#parents' => $element['#parents'],
1454
  );
1455

    
1456
  // The JavaScript stores the currently selected tab in this hidden
1457
  // field so that the active control can be restored the next time the
1458
  // form is rendered, e.g. on preview pages or when form validation
1459
  // fails.
1460
  $name = implode('__', $element['#parents']);
1461
  if (isset($form_state['values'][$name . '__active_control'])) {
1462
    $element['#default_tab'] = $form_state['values'][$name . '__active_control'];
1463
  }
1464
  $element[$name . '__active_control'] = array(
1465
    '#type' => 'hidden',
1466
    '#default_value' => $element['#default_control'],
1467
    '#attributes' => array('class' => array('multipage-active-control')),
1468
  );
1469

    
1470
  return $element;
1471
}
1472

    
1473
/**
1474
 * Returns HTML for an element's children fieldsets as multipage.
1475
 *
1476
 * @param $variables
1477
 *   An associative array containing:
1478
 *   - element: An associative array containing the properties and children of the
1479
 *     fieldset. Properties used: #children.
1480
 *
1481
 * @ingroup themeable
1482
 */
1483
function theme_multipage($variables) {
1484
  $element = $variables['element'];
1485
  // Add required JavaScript and Stylesheet.
1486
  $element['#attached']['library'][] = array('field_group', 'multipage');
1487

    
1488
  $output = '<h2 class="element-invisible">' . (!empty($element['#title']) ? $element['#title'] : t('Multipage')) . '</h2>';
1489

    
1490
  $output .= '<div class="multipage-panes">';
1491
  $output .= $element['#children'];
1492
  $output .= '</div>';
1493

    
1494
  return $output;
1495
}
1496

    
1497
/**
1498
 * Returns HTML for multipage pane.
1499
 *
1500
 * @param $variables
1501
 *   An associative array containing:
1502
 *   - element: An associative array containing the properties and children of the
1503
 *     fieldset. Properties used: #children.
1504
 *
1505
 * @ingroup themeable
1506
 */
1507
function theme_multipage_pane($variables) {
1508

    
1509
  $element = $variables['element'];
1510
  $group = $variables['element']['#group_object'];
1511
  $parent_group = $variables['element']['#parent_group_object'];
1512

    
1513
  static $multipages;
1514
  if (!isset($multipages[$group->parent_name])) {
1515
    $multipages = array($group->parent_name => 0);
1516
  }
1517
  $multipages[$parent_group->group_name]++;
1518

    
1519
  // Create a page title from the label.
1520
  $page_header = isset($parent_group->format_settings['instance_settings']['page_header']) ? $parent_group->format_settings['instance_settings']['page_header'] : 3;
1521
  switch ($page_header) {
1522
    case 1:
1523
      $title = $element['#title'];
1524
      break;
1525
    case 2:
1526
      $title = t('Step %count of %total', array('%count' => $multipages[$parent_group->group_name], '%total' => count($parent_group->children)));
1527
      break;
1528
    case 3:
1529
      $title = t('Step %count of %total !label', array('%count' => $multipages[$parent_group->group_name], '%total' => count($parent_group->children), '!label' => $element['#title']));
1530
      break;
1531
    case 0:
1532
    default:
1533
      $title = '';
1534
      break;
1535
  }
1536

    
1537
  element_set_attributes($element, array('id'));
1538
  _form_set_class($element, array('form-wrapper'));
1539

    
1540
  $output = '<div' . drupal_attributes($element['#attributes']) . '>';
1541
  if (!empty($element['#title'])) {
1542
    // Always wrap fieldset legends in a SPAN for CSS positioning.
1543
    $output .= '<h2 class="multipage-pane-title"><span>' . $title . '</span></h2>';
1544
  }
1545
  $output .= '<div class="fieldset-wrapper multipage-pane-wrapper">';
1546
  if (!empty($element['#description'])) {
1547
    $output .= '<div class="fieldset-description">' . $element['#description'] . '</div>';
1548
  }
1549
  $output .= $element['#children'];
1550
  if (isset($element['#value'])) {
1551
    $output .= $element['#value'];
1552
  }
1553

    
1554
  // Add a page counter if needed.
1555
  // counter array(0 => t('No'), 1 => t('Format 1 / 10'), 2 => t('The count number only'));
1556
  $page_counter_format = isset($parent_group->format_settings['instance_settings']['page_counter']) ? $parent_group->format_settings['instance_settings']['page_counter'] : 1;
1557
  $multipage_element['#page_counter_rendered'] = '';
1558
  if ($page_counter_format == 1) {
1559
    $output .= t('<span class="multipage-counter">%count / %total</span>', array('%count' => $multipages[$parent_group->group_name], '%total' => count($parent_group->children)));
1560
  }
1561
  elseif ($page_counter_format == 2) {
1562
    $output .=  t('<span class="multipage-counter">%count</span>', array('%count' => $multipages[$parent_group->group_name]));
1563
  }
1564

    
1565
  $output .= '</div>';
1566
  $output .= "</div>\n";
1567

    
1568
  return $output;
1569

    
1570
}
1571

    
1572
/**
1573
 * Get all groups.
1574
 *
1575
 * @param $entity_type
1576
 *   The name of the entity.
1577
 * @param $bundle
1578
 *   The name of the bundle.
1579
 * @param $view_mode
1580
 *   The view mode.
1581
 * @param $reset.
1582
 *   Whether to reset the cache or not.
1583
 */
1584
function field_group_info_groups($entity_type = NULL, $bundle = NULL, $view_mode = NULL, $reset = FALSE) {
1585
  static $groups = FALSE;
1586

    
1587
  if (!$groups || $reset) {
1588
    if (!$reset && $cached = cache_get('field_groups', 'cache_field')) {
1589
      $groups = $cached->data;
1590
    }
1591
    else {
1592
      $ctools_export_load_object = &drupal_static('ctools_export_load_object');
1593
      $ctools_export_load_object_all = &drupal_static('ctools_export_load_object_all');
1594
      unset($ctools_export_load_object['field_group']);
1595
      unset($ctools_export_load_object_all['field_group']);
1596
      $groups = field_group_read_groups();
1597
      cache_set('field_groups', $groups, 'cache_field');
1598
    }
1599
  }
1600

    
1601
  if (!isset($entity_type)) {
1602
    return $groups;
1603
  }
1604
  elseif (!isset($bundle) && isset($groups[$entity_type])) {
1605
    return $groups[$entity_type];
1606
  }
1607
  elseif (!isset($view_mode) && isset($groups[$entity_type][$bundle])) {
1608
    return $groups[$entity_type][$bundle];
1609
  }
1610
  elseif (isset($groups[$entity_type][$bundle][$view_mode])) {
1611
    return $groups[$entity_type][$bundle][$view_mode];
1612
  }
1613
  return array();
1614
}
1615

    
1616
/**
1617
 * Read all groups.
1618
 *
1619
 * @param array $conditions
1620
 *   Parameters for the query, as elements of the $conditions array.
1621
 *   'entity_type' The name of the entity type.
1622
 *   'bundle' The name of the bundle.
1623
 *   'mode' The view mode.
1624
 *
1625
 * @param boolean $enabled
1626
 *   Return enabled or disabled groups.
1627
 *
1628
 * @return array
1629
 *   Array of groups.
1630
 */
1631
function field_group_read_groups($conditions = array(), $enabled = TRUE) {
1632

    
1633
  $groups = array();
1634
  ctools_include('export');
1635

    
1636
  if (empty($conditions)) {
1637
    $records = ctools_export_load_object('field_group');
1638
  }
1639
  else {
1640
    $records = ctools_export_load_object('field_group', 'conditions', $conditions);
1641
  }
1642

    
1643
  foreach ($records as $group) {
1644

    
1645
    // Return only enabled groups.
1646
    if ($enabled && isset($group->disabled) && $group->disabled) {
1647
      continue;
1648
    }
1649
    // Return only disabled groups.
1650
    elseif (!$enabled && (!isset($group->disabled) || !$group->disabled)) {
1651
      continue;
1652
    }
1653

    
1654
    $groups[$group->entity_type][$group->bundle][$group->mode][$group->group_name] = field_group_unpack($group);
1655

    
1656
  }
1657
  drupal_alter('field_group_info', $groups);
1658
  return $groups;
1659

    
1660
}
1661

    
1662
/**
1663
 * Utility function to recreate identifiers.
1664
 */
1665
function _field_group_recreate_identifiers() {
1666

    
1667
  // Migrate the field groups so they have a unique identifier.
1668
  $result = db_select('field_group', 'fg')
1669
    ->fields('fg')
1670
    ->execute();
1671
  $rows = array();
1672
  foreach($result as $row) {
1673
    $row->identifier = $row->group_name . '|' . $row->entity_type . '|' . $row->bundle . '|' . $row->mode;
1674
    $row->data = unserialize($row->data);
1675
    $rows[] = $row;
1676
  }
1677
  foreach ($rows as $row) {
1678
    drupal_write_record('field_group', $row, array('id'));
1679
  }
1680

    
1681
}
1682

    
1683
/**
1684
 * Checks if a field_group exists in required context.
1685
 *
1686
 * @param String $group_name
1687
 *   The name of the group.
1688
 * @param String $entity_type
1689
 *   The name of the entity.
1690
 * @param String $bundle
1691
 *   The bundle for the entity.
1692
 * @param String $mode
1693
 *   The view mode context the group will be rendered.
1694
 */
1695
function field_group_exists($group_name, $entity_type, $bundle, $mode) {
1696
  $groups = field_group_read_groups();
1697
  return !empty($groups[$entity_type][$bundle][$mode][$group_name]);
1698
}
1699

    
1700
/**
1701
 * Unpacks a database row in a FieldGroup object.
1702
 * @param $packed_group
1703
 *   Database result object with stored group data.
1704
 * @return $group
1705
 *   Field group object.
1706
 */
1707
function field_group_unpack($packed_group) {
1708
  if (empty($packed_group->data)) {
1709
    return $packed_group;
1710
  }
1711

    
1712
  // Extract unserialized data.
1713
  $group = clone $packed_group;
1714
  $data = $group->data;
1715
  unset($group->data);
1716
  $group->label = isset($data['label']) ? $data['label'] : '';
1717
  $group->weight = isset($data['weight']) ? $data['weight'] : '';
1718
  $group->children = isset($data['children']) ? $data['children'] : '';
1719
  $group->format_type = !empty($data['format_type']) ? $data['format_type'] : 'fieldset';
1720
  if (isset($data['format_settings'])) {
1721
    $group->format_settings = $data['format_settings'];
1722
  }
1723

    
1724
  return $group;
1725
}
1726

    
1727
/**
1728
 * Packs a FieldGroup object into a database row.
1729
 * @param $group
1730
 *   FieldGroup object.
1731
 * @return $record
1732
 *   Database row object, ready to be inserted/update
1733
 */
1734
function field_group_pack($group) {
1735

    
1736
  $record = clone $group;
1737
  $record->data = array(
1738
    'label' => $record->label,
1739
    'weight' => $record->weight,
1740
    'children' => $record->children,
1741
    'format_type' => !empty($record->format_type) ? $record->format_type : 'fieldset',
1742
  );
1743
  if (isset($record->format_settings)) {
1744
    $record->data['format_settings'] = $record->format_settings;
1745
  }
1746
  return $record;
1747
}
1748

    
1749
/**
1750
 * Delete a field group.
1751
 * This function is also called by ctools export when calls are
1752
 * made through ctools_export_crud_delete().
1753
 *
1754
 * @param $group
1755
 *   A group definition.
1756
 * @param $ctools_crud
1757
 *  Is this function called by the ctools crud delete.
1758
 */
1759
function field_group_group_export_delete($group, $ctools_crud = TRUE) {
1760

    
1761
  $query = db_delete('field_group');
1762

    
1763
  if (isset($group->identifier)) {
1764
    $query->condition('identifier', $group->identifier);
1765
    if (!$ctools_crud) {
1766
      ctools_export_crud_disable('field_group', $group->identifier);
1767
    }
1768
  }
1769
  elseif (isset($group->id)) {
1770
    $query->condition('id', $group->id);
1771
  }
1772

    
1773
  if (!empty($group->mode)) {
1774
    $query->condition('mode', $group->mode);
1775
  }
1776

    
1777
  $query->execute();
1778

    
1779
  cache_clear_all('field_groups', 'cache_field');
1780
  module_invoke_all('field_group_delete_field_group', $group);
1781

    
1782
}
1783

    
1784
/**
1785
 * field_group_group_save().
1786
 *
1787
 * Saves a group definition.
1788
 * This function is called by ctools export when calls are made
1789
 * through ctools_export_crud_save().
1790
 *
1791
 * @param $group
1792
 *   A group definition.
1793
 */
1794
function field_group_group_save(& $group) {
1795

    
1796
  // Prepare the record.
1797
  $object = field_group_pack($group);
1798

    
1799
  if (isset($object->export_type) && $object->export_type & EXPORT_IN_DATABASE) {
1800
    // Existing record.
1801
    $update = array('id');
1802
    module_invoke_all('field_group_update_field_group', $object);
1803
  }
1804
  else {
1805
    // New record.
1806
    $update = array();
1807
    $object->export_type = EXPORT_IN_DATABASE;
1808
    module_invoke_all('field_group_create_field_group', $object);
1809
  }
1810

    
1811
  return drupal_write_record('field_group', $object, $update);
1812

    
1813
}
1814

    
1815
/**
1816
 * Function to retrieve all format possibilities for the fieldgroups.
1817
 */
1818
function field_group_formatter_info($display_overview = FALSE) {
1819
  $cache = &drupal_static(__FUNCTION__, array());
1820
  if (empty($cache)) {
1821
    if ($cached = cache_get('field_group_formatter_info', 'cache_field')) {
1822
      $formatters = $cached->data;
1823
    }
1824
    else {
1825
      $formatters = array();
1826
      $formatters += module_invoke_all('field_group_formatter_info');
1827
      $hidden_region = array(
1828
        'label' => '<' . t('Hidden') . '>',
1829
        'description' => '',
1830
        'format_types' => array(),
1831
        'instance_settings' => array(),
1832
        'default_formatter' => '',
1833
      );
1834
      //$formatters['form']['hidden'] = $hidden_region;
1835
      $formatters['display']['hidden'] = $hidden_region;
1836
      cache_set('field_group_formatter_info', $formatters, 'cache_field');
1837
    }
1838
    $cache = $formatters;
1839
  }
1840
  return $cache;
1841
}
1842

    
1843
/**
1844
 * Attach groups to the (form) build.
1845
 *
1846
 * @param Array $element
1847
 *   The part of the form.
1848
 * @param String $view_mode
1849
 *   The mode for the build.
1850
 * @param Array $form_state
1851
 *   The optional form state when in view_mode = form context.
1852
 */
1853
function field_group_attach_groups(&$element, $view_mode, $form_state = array()) {
1854

    
1855
  $entity_type = $element['#entity_type'];
1856
  $bundle = $element['#bundle'];
1857

    
1858
  $element['#groups'] = field_group_info_groups($entity_type, $bundle, $view_mode);
1859
  $element['#fieldgroups'] = $element['#groups'];
1860

    
1861
  // Create a lookup array.
1862
  $group_children = array();
1863
  foreach ($element['#groups'] as $group_name => $group) {
1864
    foreach ($group->children as $child) {
1865
      $group_children[$child] = $group_name;
1866
    }
1867
  }
1868
  $element['#group_children'] = $group_children;
1869

    
1870
}
1871

    
1872
/**
1873
 * Pre render callback for rendering groups.
1874
 * @see field_group_field_attach_form
1875
 * @param $element Form that is being rendered.
1876
 */
1877
function field_group_form_pre_render(&$element) {
1878
  return field_group_build_entity_groups($element, 'form');
1879
}
1880

    
1881
/**
1882
 * Preprocess/ Pre-render callback.
1883
 *
1884
 * @see field_group_form_pre_render()
1885
 * @see field_group_theme_registry_alter
1886
 * @see field_group_fields_nest()
1887
 * @param $vars preprocess vars or form element
1888
 * @param $type The type of object being rendered
1889
 * @return $element Array with re-arranged fields in forms.
1890
 */
1891
function field_group_build_entity_groups(&$vars, $type) {
1892

    
1893
  if ($type == 'form') {
1894
    $element = &$vars;
1895
    $nest_vars = NULL;
1896
  }
1897
  else {
1898
    $element = &$vars['elements'];
1899
    $nest_vars = &$vars;
1900
  }
1901

    
1902
  // No groups on the entity.
1903
  if (empty($element['#fieldgroups'])) {
1904
    return $element;
1905
  }
1906

    
1907
  // Nest the fields in the corresponding field groups.
1908
  field_group_fields_nest($element, $nest_vars);
1909

    
1910
  // Allow others to alter the pre_rendered build.
1911
  drupal_alter('field_group_build_pre_render', $element);
1912

    
1913
  // Return the element on forms.
1914
  if ($type == 'form') {
1915
    return $element;
1916
  }
1917

    
1918
  // No groups on the entity. Prerender removed empty field groups.
1919
  if (empty($element['#fieldgroups'])) {
1920
    return $element;
1921
  }
1922

    
1923
  // Put groups inside content if we are rendering an entity_view.
1924
  foreach ($element['#fieldgroups'] as $group) {
1925
    if (!empty($element[$group->group_name]) && $type != 'user_profile') {
1926
      $vars['content'][$group->group_name] = $element[$group->group_name];
1927
    }
1928
    elseif (!empty($element[$group->group_name])) {
1929
      $vars['user_profile'][$group->group_name] = $element[$group->group_name];
1930
    }
1931
  }
1932

    
1933
  // New css / js can be attached.
1934
  drupal_process_attached($element);
1935
}
1936

    
1937
/**
1938
 * Recursive function to nest fields in the field groups.
1939
 *
1940
 * This function will take out all the elements in the form and
1941
 * place them in the correct container element, a fieldgroup.
1942
 * The current group element in the loop is passed recursively so we can
1943
 * stash fields and groups in it while we go deeper in the array.
1944
 * @param Array $element
1945
 *   The current element to analyse for grouping.
1946
 * @param Array $vars
1947
 *   Rendering vars from the entity being viewed.
1948
 */
1949
function field_group_fields_nest(&$element, &$vars = NULL) {
1950

    
1951
  // Create all groups and keep a flat list of references to these groups.
1952
  $group_references = array();
1953
  foreach ($element['#fieldgroups'] as $group_name => $group) {
1954
    // Construct own weight, as some fields (for example preprocess fields) don't have weight set.
1955
    $element[$group_name] = array();
1956
    $group_references[$group_name] = &$element[$group_name];
1957
  }
1958

    
1959
  // Loop through all form children looking for those that are supposed to be
1960
  // in groups, and insert placeholder element for the new group field in the
1961
  // correct location within the form structure.
1962
  $element_clone = array();
1963
  foreach (element_children($element) as $child_name) {
1964
    $element_clone[$child_name] = $element[$child_name];
1965
    // If this element is in a group, create the placeholder element.
1966
    if (isset($element['#group_children'][$child_name])) {
1967
      $element_clone[$element['#group_children'][$child_name]] = array();
1968
    }
1969
  }
1970
  $element = array_merge($element_clone, $element);
1971

    
1972
  // Move all children to their parents. Use the flat list of references for
1973
  // direct access as we don't know where in the root_element hierarchy the
1974
  // parent currently is situated.
1975
  foreach ($element['#group_children'] as $child_name => $parent_name) {
1976

    
1977
    // Entity being viewed
1978
    if ($vars) {
1979
      // If not a group, check vars['content'] for empty field.
1980
      if (!isset($element['#fieldgroups'][$child_name]) && isset($vars['content'][$child_name])) {
1981
        $group_references[$parent_name][$child_name] = $vars['content'][$child_name];
1982
        unset($vars['content'][$child_name]);
1983
      }
1984
      elseif (!isset($element['#fieldgroups'][$child_name]) && isset($vars['user_profile'][$child_name])) {
1985
        $group_references[$parent_name][$child_name] = $vars['user_profile'][$child_name];
1986
        unset($vars['user_profile'][$child_name]);
1987
      }
1988
      // If this is a group, we have to use a reference to keep the reference
1989
      // list intact (but if it is a field we don't mind).
1990
      else {
1991
        $group_references[$parent_name][$child_name] = &$element[$child_name];
1992
        unset($element[$child_name]);
1993
      }
1994
    }
1995
    // Form being viewed
1996
    else {
1997

    
1998
      // Block denied fields (#access) before they are put in groups.
1999
      // Fields (not groups) that don't have children (like field_permissions) are removed
2000
      // in field_group_field_group_build_pre_render_alter.
2001
      if (isset($element[$child_name]) && (!isset($element[$child_name]['#access']) || $element[$child_name]['#access'])) {
2002
        // If this is a group, we have to use a reference to keep the reference
2003
        // list intact (but if it is a field we don't mind).
2004
        $group_references[$parent_name][$child_name] = &$element[$child_name];
2005
        $group_references[$parent_name]['#weight'] = $element['#fieldgroups'][$parent_name]->weight;
2006
      }
2007

    
2008
      // The child has been copied to its parent: remove it from the root element.
2009
      unset($element[$child_name]);
2010
    }
2011

    
2012
  }
2013

    
2014
  // Bring extra element wrappers to achieve a grouping of fields.
2015
  // This will mainly be prefix and suffix altering.
2016
  foreach ($element['#fieldgroups'] as $group_name => $group) {
2017
    field_group_pre_render($group_references[$group_name], $group, $element);
2018
  }
2019

    
2020
}
2021

    
2022
/**
2023
 * Function to pre render the field group element.
2024
 *
2025
 * @see field_group_fields_nest()
2026
 *
2027
 * @param $element Array of group element that needs to be created!
2028
 * @param $group Object with the group information.
2029
 * @param $form The form object itself.
2030
 */
2031
function field_group_pre_render(& $element, $group, & $form) {
2032

    
2033
  // Only run the pre_render function if the group has elements.
2034
  // $group->group_name
2035
  if ($element == array()) {
2036
    return;
2037
  }
2038

    
2039
  // Let modules define their wrapping element.
2040
  // Note that the group element has no properties, only elements.
2041
  foreach (module_implements('field_group_pre_render') as $module) {
2042
    $function = $module . '_field_group_pre_render';
2043
    if (function_exists($function)) {
2044
      // The intention here is to have the opportunity to alter the
2045
      // elements, as defined in hook_field_group_formatter_info.
2046
      // Note, implement $element by reference!
2047
      $function($element, $group, $form);
2048
    }
2049
  }
2050

    
2051
  // Allow others to alter the pre_render.
2052
  drupal_alter('field_group_pre_render', $element, $group, $form);
2053

    
2054
}
2055

    
2056
/**
2057
 * Hides field groups including children in a render array.
2058
 *
2059
 * @param array $element
2060
 *   A render array. Can be a form, node, user, ...
2061
 * @param array $group_names
2062
 *   An array of field group names that should be hidden.
2063
 */
2064
function field_group_hide_field_groups(&$element, $group_names) {
2065
  foreach ($group_names as $group_name) {
2066
    if (isset($element['#fieldgroups'][$group_name]) && isset($element['#group_children'])) {
2067
      // Hide the field group.
2068
      $element['#fieldgroups'][$group_name]->format_type = 'hidden';
2069
      // Hide the elements inside the field group.
2070
      $sub_groups = array();
2071
      foreach (array_keys($element['#group_children'], $group_name) as $field_name) {
2072
        if (isset($element['#fieldgroups'][$field_name])) {
2073
          $sub_groups[] = $field_name;
2074
        } else {
2075
          $element[$field_name]['#access'] = FALSE;
2076
        }
2077
      }
2078
      field_group_hide_field_groups($element, $sub_groups);
2079
    }
2080
  }
2081
}
2082

    
2083
/**
2084
 * Calculates html classes for a group.
2085
 */
2086
function _field_group_get_html_classes(&$group) {
2087

    
2088
  if (isset($group->format_settings['formatter'])) {
2089
    $group->collapsible = in_array($group->format_settings['formatter'], array('collapsible', 'collapsed'));
2090
    // Open or closed horizontal or vertical tabs will be collapsible by default.
2091
    if ($group->format_type == 'tab' || $group->format_type == 'htab') {
2092
      $group->collapsible = TRUE;
2093
    }
2094
    $group->collapsed = in_array($group->format_settings['formatter'], array('collapsed', 'closed'));
2095
  }
2096

    
2097
  $classes = new stdClass();
2098

    
2099
  // Prepare extra classes, required and optional ones.
2100
  $optional = array(str_replace('_', '-', $group->group_name));
2101
  $required = array();
2102
  if ($group->format_type == 'multipage') {
2103
    $required[] = 'field-group-' . $group->format_type;
2104
  }
2105
  else {
2106
    $optional[] = 'field-group-' . $group->format_type;
2107
  }
2108

    
2109
  if (isset($group->format_settings['formatter']) && $group->collapsible) {
2110
    $required[] = 'collapsible';
2111
    if ($group->collapsed) {
2112
      $required[] = 'collapsed';
2113
    }
2114
  }
2115

    
2116
  if (isset($group->format_settings['instance_settings'])) {
2117

    
2118
    // Add a required-fields class to trigger the js.
2119
    if (!empty($group->format_settings['instance_settings']['required_fields'])) {
2120
      $required[] = 'required-fields';
2121
    }
2122

    
2123
    // Add user selected classes.
2124
    if (!empty($group->format_settings['instance_settings']['classes'])) {
2125
      $required[] = check_plain($group->format_settings['instance_settings']['classes']);
2126
    }
2127

    
2128
    // Extra required classes for div.
2129
    if ($group->format_type == 'div') {
2130
      if ($group->format_settings['formatter'] != 'open') {
2131

    
2132
        $speed = isset($group->format_settings['instance_settings']['speed']) ? $group->format_settings['instance_settings']['speed'] : 'none';
2133
        $required[] = 'speed-' . $speed;
2134

    
2135
        $effect = isset($group->format_settings['instance_settings']['effect']) ? $group->format_settings['instance_settings']['effect'] : 'none';
2136
        $required[] = 'effect-' . $effect;
2137
      }
2138
    }
2139

    
2140
    // Extra required classes for accordions.
2141
    elseif ($group->format_type == 'accordion') {
2142
      $required[] = 'field-group-' . $group->format_type . '-wrapper';
2143
      $effect = isset($group->format_settings['instance_settings']['effect']) ? $group->format_settings['instance_settings']['effect'] : 'none';
2144
      $required[] = 'effect-' . $effect;
2145
    }
2146

    
2147
  }
2148

    
2149
  $classes->required = $required;
2150
  $classes->optional = $optional;
2151

    
2152
  return $classes;
2153
}
2154

    
2155
/**
2156
 * Get the default formatter settings for a given formatter and a mode.
2157
 */
2158
function _field_group_get_default_formatter_settings($format_type, $mode) {
2159

    
2160
  $field_group_types = field_group_formatter_info();
2161
  $display_mode = $mode == 'form' ? 'form' : 'display';
2162
  $formatter = $field_group_types[$display_mode][$format_type];
2163

    
2164
  return array(
2165
    'formatter' => isset($formatter['default_formatter']) ? $formatter['default_formatter'] : '',
2166
    'instance_settings' => $formatter['instance_settings']
2167
  );
2168
}
2169