Projet

Général

Profil

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

root / drupal7 / sites / all / modules / field_collection / field_collection.module @ 950416da

1
<?php
2

    
3
/**
4
 * @file
5
 * Module implementing field collection field type.
6
 */
7

    
8
/**
9
 * Implements hook_help().
10
 */
11
function field_collection_help($path, $arg) {
12
  switch ($path) {
13
    case 'admin/help#field_collection':
14
      $output = '';
15
      $output .= '<h3>' . t('About') . '</h3>';
16
      $output .= '<p>' . t('The field collection module provides a field, to which any number of fields can be attached. See the <a href="@field-help">Field module help page</a> for more information about fields.', array('@field-help' => url('admin/help/field'))) . '</p>';
17
      return $output;
18
  }
19
}
20

    
21
/**
22
 * Implements hook_form_alter().
23
 *
24
 * Checks for a value set by the embedded widget so fields are not displayed
25
 * with the 'all languages' hint incorrectly.
26
 */
27
function field_collection_form_alter(&$form, &$form_state) {
28
  if (!empty($form['#field_collection_translation_fields'])) {
29
    foreach ($form['#field_collection_translation_fields'] as $address) {
30
      drupal_array_set_nested_value($form, array_merge($address, array('#multilingual')), TRUE);
31
    }
32
  }
33
}
34

    
35
/**
36
 * Implements hook_form_FORM_ID_alter() for field_ui_field_overview_form().
37
 *
38
 * Make the names of the field collection fields into links to edit the fields
39
 * for that field collection on the host's field edit page.
40
 */
41
function field_collection_form_field_ui_field_overview_form_alter(&$form, &$form_state) {
42
  if (count($form['#fields'])) {
43
    foreach ($form['fields'] as $fieldname => $field) {
44
      if (!isset($field['type']['#title'])) {
45
        continue;
46
      }
47
      if ($field['type']['#title'] == 'Field collection') {
48
        $form['fields'][$fieldname]['field_name']['#markup'] =
49
          l($form['fields'][$fieldname]['field_name']['#markup'], 'admin/structure/field-collections/' . str_replace('_', '-', $fieldname) . '/fields');
50
      }
51
    }
52
  }
53
}
54

    
55
/**
56
 * Implements hook_ctools_plugin_directory().
57
 */
58
function field_collection_ctools_plugin_directory($module, $plugin) {
59
  if ($module == 'ctools') {
60
    return 'ctools/' . $plugin;
61
  }
62
}
63

    
64
/**
65
 * Implements hook_entity_info().
66
 */
67
function field_collection_entity_info() {
68
  $return['field_collection_item'] = array(
69
    'label' => t('Field collection item'),
70
    'label callback' => 'entity_class_label',
71
    'uri callback' => 'entity_class_uri',
72
    'entity class' => 'FieldCollectionItemEntity',
73
    'controller class' => 'EntityAPIController',
74
    'base table' => 'field_collection_item',
75
    'revision table' => 'field_collection_item_revision',
76
    'fieldable' => TRUE,
77
    // For integration with Redirect module.
78
    // @see http://drupal.org/node/1263884
79
    'redirect' => FALSE,
80
    'entity keys' => array(
81
      'id' => 'item_id',
82
      'revision' => 'revision_id',
83
      'bundle' => 'field_name',
84
    ),
85
    'module' => 'field_collection',
86
    'view modes' => array(
87
      'full' => array(
88
        'label' => t('Full content'),
89
        'custom settings' => FALSE,
90
      ),
91
    ),
92
    'access callback' => 'field_collection_item_access',
93
    'deletion callback' => 'field_collection_item_delete',
94
    'metadata controller class' => 'FieldCollectionItemMetadataController',
95
    'translation' => array(
96
      'entity_translation' => array(
97
        'class' => 'EntityTranslationFieldCollectionItemHandler',
98
      ),
99
    ),
100
  );
101

    
102
  // Add info about the bundles. We do not use field_info_fields() but directly
103
  // use field_read_fields() as field_info_fields() requires built entity info
104
  // to work.
105
  foreach (field_read_fields(array('type' => 'field_collection')) as $field_name => $field) {
106
    $return['field_collection_item']['bundles'][$field_name] = array(
107
      'label' => t('Field collection @field', array('@field' => $field_name)),
108
      'admin' => array(
109
        'path' => 'admin/structure/field-collections/%field_collection_field_name',
110
        'real path' => 'admin/structure/field-collections/' . strtr($field_name, array('_' => '-')),
111
        'bundle argument' => 3,
112
        'access arguments' => array('administer field collections'),
113
      ),
114
    );
115

    
116
    $path = field_collection_field_get_path($field) . '/%field_collection_item';
117
    // Enable the first available path scheme as default one.
118
    if (!isset($return['field_collection_item']['translation']['entity_translation']['base path'])) {
119
      $return['field_collection_item']['translation']['entity_translation']['base path'] = $path;
120
      $return['field_collection_item']['translation']['entity_translation']['path wildcard'] = '%field_collection_item';
121
      $return['field_collection_item']['translation']['entity_translation']['default_scheme'] = $field_name;
122
    }
123
    else {
124
      $return['field_collection_item']['translation']['entity_translation']['path schemes'][$field_name] = array(
125
        'base path' => $path,
126
      );
127
    }
128
  }
129

    
130
  if (module_exists('entitycache')) {
131
    $return['field_collection_item']['field cache'] = FALSE;
132
    $return['field_collection_item']['entity cache'] = TRUE;
133
  }
134

    
135
  return $return;
136
}
137

    
138
/**
139
 * Provide the original entity language.
140
 *
141
 * If a language property is defined for the current entity we synchronize the
142
 * field value using the entity language, otherwise we fall back to
143
 * LANGUAGE_NONE.
144
 *
145
 * @param $entity_type
146
 * @param $entity
147
 *
148
 * @return string
149
 *   A language code
150
 */
151
function field_collection_entity_language($entity_type, $entity) {
152
  if (module_exists('entity_translation') && entity_translation_enabled($entity_type)) {
153
    $handler = entity_translation_get_handler($entity_type, $entity);
154
    $langcode = $handler->getLanguage();
155
  }
156
  else {
157
    $langcode = entity_language($entity_type, $entity);
158
  }
159
  return !empty($langcode) ? $langcode : LANGUAGE_NONE;
160
}
161

    
162
/**
163
 * Menu callback for loading the bundle names.
164
 */
165
function field_collection_field_name_load($arg) {
166
  $field_name = strtr($arg, array('-' => '_'));
167
  if (($field = field_info_field($field_name)) && $field['type'] == 'field_collection') {
168
    return $field_name;
169
  }
170
}
171

    
172
/**
173
 * Loads a field collection item.
174
 *
175
 * @return
176
 *   The field collection item entity or FALSE.
177
 */
178
function field_collection_item_load($item_id, $reset = FALSE) {
179
  $result = field_collection_item_load_multiple(array($item_id), array(), $reset);
180
  return $result ? reset($result) : FALSE;
181
}
182

    
183
/**
184
 * Loads a field collection revision.
185
 *
186
 * @param $revision_id
187
 *   The field collection revision ID.
188
 */
189
function field_collection_item_revision_load($revision_id) {
190
  return entity_revision_load('field_collection_item', $revision_id);
191
}
192

    
193
/**
194
 * Loads field collection items.
195
 *
196
 * @return
197
 *   An array of field collection item entities.
198
 */
199
function field_collection_item_load_multiple($ids = array(), $conditions = array(), $reset = FALSE) {
200
  return entity_load('field_collection_item', $ids, $conditions, $reset);
201
}
202

    
203
/**
204
 * Implements hook_menu().
205
 */
206
function field_collection_menu() {
207
  $items = array();
208
  if (module_exists('field_ui')) {
209
    $items['admin/structure/field-collections'] = array(
210
      'title' => 'Field collections',
211
      'description' => 'Manage fields on field collections.',
212
      'page callback' => 'field_collections_overview',
213
      'access arguments' => array('administer field collections'),
214
      'type' => MENU_NORMAL_ITEM,
215
      'file' => 'field_collection.admin.inc',
216
    );
217
  }
218

    
219
  // Add menu paths for viewing/editing/deleting field collection items.
220
  foreach (field_info_fields() as $field) {
221
    if ($field['type'] == 'field_collection') {
222
      $path = field_collection_field_get_path($field);
223
      $count = count(explode('/', $path));
224

    
225
      $items[$path . '/%field_collection_item'] = array(
226
        'page callback' => 'field_collection_item_page_view',
227
        'page arguments' => array($count),
228
        'access callback' => 'entity_access',
229
        'access arguments' => array('view', 'field_collection_item', $count),
230
        'file' => 'field_collection.pages.inc',
231
      );
232
      $items[$path . '/%field_collection_item/view'] = array(
233
        'title' => 'View',
234
        'type' => MENU_DEFAULT_LOCAL_TASK,
235
        'weight' => -10,
236
      );
237
      $items[$path . '/%field_collection_item/edit'] = array(
238
        'page callback' => 'drupal_get_form',
239
        'page arguments' => array('field_collection_item_form', $count),
240
        'access callback' => 'entity_access',
241
        'access arguments' => array('update', 'field_collection_item', $count),
242
        'title' => 'Edit',
243
        'type' => MENU_LOCAL_TASK,
244
        'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
245
        'file' => 'field_collection.pages.inc',
246
      );
247
      $items[$path . '/%field_collection_item/delete'] = array(
248
        'page callback' => 'drupal_get_form',
249
        'page arguments' => array('field_collection_item_delete_confirm', $count),
250
        'access callback' => 'entity_access',
251
        'access arguments' => array('delete', 'field_collection_item', $count),
252
        'title' => 'Delete',
253
        'type' => MENU_LOCAL_TASK,
254
        'context' => MENU_CONTEXT_INLINE,
255
        'file' => 'field_collection.pages.inc',
256
      );
257
      // Add entity type and the entity id as additional arguments.
258
      $items[$path . '/add/%/%'] = array(
259
        'page callback' => 'field_collection_item_add',
260
        'page arguments' => array($field['field_name'], $count + 1, $count + 2),
261
        // The pace callback takes care of checking access itself.
262
        'access callback' => TRUE,
263
        'file' => 'field_collection.pages.inc',
264
      );
265
      // Add menu items for dealing with revisions.
266
      $items[$path . '/%field_collection_item/revisions/%field_collection_item_revision'] = array(
267
        'page callback' => 'field_collection_item_page_view',
268
        'page arguments' => array($count + 2),
269
        'access callback' => 'entity_access',
270
        'access arguments' => array('view', 'field_collection_item', $count + 2),
271
        'file' => 'field_collection.pages.inc',
272
      );
273
    }
274
  }
275

    
276
  return $items;
277
}
278

    
279
/**
280
 * Implements hook_menu_alter() to fix the field collections admin UI tabs.
281
 */
282
function field_collection_menu_alter(&$items) {
283
  if (module_exists('field_ui') && isset($items['admin/structure/field-collections/%field_collection_field_name/fields'])) {
284
    // Make the fields task the default local task.
285
    $items['admin/structure/field-collections/%field_collection_field_name'] = $items['admin/structure/field-collections/%field_collection_field_name/fields'];
286
    $item = &$items['admin/structure/field-collections/%field_collection_field_name'];
287
    $item['type'] = MENU_NORMAL_ITEM;
288
    $item['title'] = 'Manage fields';
289
    $item['title callback'] = 'field_collection_admin_page_title';
290
    $item['title arguments'] = array(3);
291

    
292
    $items['admin/structure/field-collections/%field_collection_field_name/fields'] = array(
293
      'title' => 'Manage fields',
294
      'type' => MENU_DEFAULT_LOCAL_TASK,
295
      'weight' => 1,
296
    );
297
  }
298
}
299

    
300
/**
301
 * Menu title callback.
302
 */
303
function field_collection_admin_page_title($field_name) {
304
  return t('Field collection @field_name', array('@field_name' => $field_name));
305
}
306

    
307
/**
308
 * Implements hook_admin_paths().
309
 */
310
function field_collection_admin_paths() {
311
  if (variable_get('node_admin_theme')) {
312
    return array(
313
      'field-collection/*/*/edit' => TRUE,
314
      'field-collection/*/*/delete' => TRUE,
315
      'field-collection/*/add/*/*' => TRUE,
316
    );
317
  }
318
}
319

    
320
/**
321
 * Implements hook_permission().
322
 */
323
function field_collection_permission() {
324
  return array(
325
    'administer field collections' => array(
326
      'title' => t('Administer field collections'),
327
      'description' => t('Create and delete fields on field collections.'),
328
    ),
329
  );
330
}
331

    
332
/**
333
 * Determines whether the given user has access to a field collection.
334
 *
335
 * @param $op
336
 *   The operation being performed. One of 'view', 'update', 'create', 'delete'.
337
 * @param $item
338
 *   Optionally a field collection item. If nothing is given, access for all
339
 *   items is determined.
340
 * @param $account
341
 *   The user to check for. Leave it to NULL to check for the global user.
342
 * @return boolean
343
 *   Whether access is allowed or not.
344
 */
345
function field_collection_item_access($op, FieldCollectionItemEntity $item = NULL, $account = NULL) {
346
  // We do not support editing field collection revisions that are not used at
347
  // the hosts default revision as saving the host might result in a new default
348
  // revision.
349
  if (isset($item) && !$item->isInUse() && $op != 'view') {
350
    return FALSE;
351
  }
352
  if (user_access('administer field collections', $account)) {
353
    return TRUE;
354
  }
355
  if (!isset($item)) {
356
    return FALSE;
357
  }
358
  $op = $op == 'view' ? 'view' : 'edit';
359
  // Access is determined by the entity and field containing the reference.
360
  $field = field_info_field($item->field_name);
361
  $entity_access = entity_access($op == 'view' ? 'view' : 'update', $item->hostEntityType(), $item->hostEntity(), $account);
362
  return $entity_access && field_access($op, $field, $item->hostEntityType(), $item->hostEntity(), $account);
363
}
364

    
365
/**
366
 * Deletion callback
367
 */
368
function field_collection_item_delete($id) {
369
  $fci = field_collection_item_load($id);
370
  if (!empty($fci)) {
371
    $fci->delete();
372
  }
373
}
374

    
375
/**
376
 * Implements hook_theme().
377
 */
378
function field_collection_theme() {
379
  return array(
380
    'field_collection_item' => array(
381
      'render element' => 'elements',
382
      'template' => 'field-collection-item',
383
    ),
384
    'field_collection_view' => array(
385
      'render element' => 'element',
386
    ),
387
  );
388
}
389

    
390
/**
391
 * Implements hook_field_info().
392
 */
393
function field_collection_field_info() {
394
  return array(
395
    'field_collection' => array(
396
      'label' => t('Field collection'),
397
      'description' => t('This field stores references to embedded entities, which itself may contain any number of fields.'),
398
      'instance_settings' => array(),
399
      'default_widget' => 'field_collection_hidden',
400
      'default_formatter' => 'field_collection_view',
401
      // As of now there is no UI for setting the path.
402
      'settings' => array(
403
        'path' => '',
404
        'hide_blank_items' => TRUE,
405
        'hide_initial_item' => FALSE,
406
      ),
407
      // Add entity property info.
408
      'property_type' => 'field_collection_item',
409
      'property_callbacks' => array('field_collection_entity_metadata_property_callback'),
410
    ),
411
  );
412
}
413

    
414
/**
415
 * Implements hook_field_instance_settings_form().
416
 */
417
function field_collection_field_instance_settings_form($field, $instance) {
418

    
419
  $element['fieldset'] = array(
420
    '#type' => 'fieldset',
421
    '#title' => t('Default value'),
422
    '#collapsible' => FALSE,
423
    // As field_ui_default_value_widget() does, we change the #parents so that
424
    // the value below is writing to $instance in the right location.
425
    '#parents' => array('instance'),
426
  );
427
  // Be sure to set the default value to NULL, e.g. to repair old fields
428
  // that still have one.
429
  $element['fieldset']['default_value'] = array(
430
    '#type' => 'value',
431
    '#value' => NULL,
432
  );
433
  $element['fieldset']['content'] = array(
434
    '#pre' => '<p>',
435
    '#markup' => t('To specify a default value, configure it via the regular default value setting of each field that is part of the field collection. To do so, go to the <a href="!url">Manage fields</a> screen of the field collection.', array('!url' => url('admin/structure/field-collections/' . strtr($field['field_name'], array('_' => '-')) . '/fields'))),
436
    '#suffix' => '</p>',
437
  );
438
  return $element;
439
}
440

    
441
/**
442
 * Returns the base path to use for field collection items.
443
 */
444
function field_collection_field_get_path($field) {
445
  if (empty($field['settings']['path'])) {
446
    return 'field-collection/' . strtr($field['field_name'], array('_' => '-'));
447
  }
448
  return $field['settings']['path'];
449
}
450

    
451
/**
452
 * Implements hook_field_settings_form().
453
 */
454
function field_collection_field_settings_form($field, $instance) {
455
  $form['hide_blank_items'] = array(
456
    '#type' => 'checkbox',
457
    '#title' => t('Hide blank items'),
458
    '#default_value' => $field['settings']['hide_blank_items'],
459
    '#description' => t('Ordinarily a new blank item will be added to unlimited cardinality fields whenever they appear in a form.  Checking this will prevent the blank item from appearing if the field already contains data.'),
460
    '#weight' => 10,
461
    '#states' => array(
462
      // Show the setting if the cardinality is -1.
463
      'visible' => array(
464
        ':input[name="field[cardinality]"]' => array('value' => '-1'),
465
      ),
466
    ),
467
  );
468
  $form['hide_initial_item'] = array(
469
    '#type' => 'checkbox',
470
    '#title' => t('Hide initial item'),
471
    '#default_value' => $field['settings']['hide_initial_item'],
472
    '#description' => t('Prevent the default blank item from appearing even if the field has no data yet.  If checked, the user must explicitly add the field collection.'),
473
    '#weight' => 11,
474
    '#states' => array(
475
      // Show the setting if the cardinality is -1 and hide_blank_items is checked.
476
      'visible' => array(
477
        ':input[name="field[cardinality]"]' => array('value' => '-1'),
478
        ':input[name="field[settings][hide_blank_items]"]' => array('checked' => TRUE),
479
      ),
480
    ),
481
  );
482
  return $form;
483
}
484

    
485
/**
486
 * Implements hook_field_insert().
487
 */
488
function field_collection_field_insert($host_entity_type, $host_entity, $field, $instance, $langcode, &$items) {
489
  foreach ($items as &$item) {
490
    if ($entity = field_collection_field_get_entity($item)) {
491
      if (!empty($host_entity->is_new) && empty($entity->is_new)) {
492
        // If the host entity is new but we have a field_collection that is not
493
        // new, it means that its host is being cloned. Thus we need to clone
494
        // the field collection entity as well.
495
        $new_entity = clone $entity;
496
        $new_entity->item_id = NULL;
497
        $new_entity->revision_id = NULL;
498
        $new_entity->is_new = TRUE;
499
        $entity = $new_entity;
500
      }
501
      if (!empty($entity->is_new)) {
502
        $entity->setHostEntity($host_entity_type, $host_entity, field_collection_entity_language($host_entity_type, $host_entity), FALSE);
503
      }
504
      $entity->save(TRUE);
505
      $item = array(
506
        'value' => $entity->item_id,
507
        'revision_id' => $entity->revision_id,
508
      );
509
    }
510
  }
511
}
512

    
513
/**
514
 * Implements hook_field_update().
515
 *
516
 * Care about removed field collection items.
517
 *
518
 * Support saving field collection items in @code $item['entity'] @endcode. This
519
 * may be used to seamlessly create field collection items during host-entity
520
 * creation or to save changes to the host entity and its collections at once.
521
 */
522
function field_collection_field_update($host_entity_type, $host_entity, $field, $instance, $langcode, &$items) {
523
  // When entity language is changed field values are moved to the new language
524
  // and old values are marked as removed. We need to avoid processing them in
525
  // this case.
526
  $entity_langcode = field_collection_entity_language($host_entity_type, $host_entity);
527
  $original = isset($host_entity->original) ? $host_entity->original : $host_entity;
528
  $original_langcode = field_collection_entity_language($host_entity_type, $original);
529
  $langcode = $langcode == $original_langcode ? $entity_langcode : $langcode;
530

    
531
  $top_host = $host_entity;
532
  while (method_exists($top_host, 'hostEntity')) {
533
    $top_host = $top_host->hostEntity();
534
  }
535

    
536
  // Prevent workbench moderation from deleting field collections or paragraphs
537
  // on node_save() during workbench_moderation_store(), when
538
  // $host_entity->revision == 0.
539
  if (!empty($top_host->workbench_moderation['updating_live_revision'])) {
540
    return;
541
  }
542

    
543
  // Load items from the original entity.
544
  $items_original = !empty($original->{$field['field_name']}[$langcode]) ? $original->{$field['field_name']}[$langcode] : array();
545
  $original_by_id = array_flip(field_collection_field_item_to_ids($items_original));
546

    
547
  foreach ($items as $delta => &$item) {
548
    // In case the entity has been changed / created, save it and set the id.
549
    // If the host entity creates a new revision, save new item-revisions as
550
    // well.
551
    if (isset($item['entity']) || !empty($host_entity->revision)) {
552
      if ($entity = field_collection_field_get_entity($item)) {
553
        // If the host entity is saved as new revision, do the same for the item.
554
        if (!empty($host_entity->revision) || !empty($host_entity->is_new_revision)) {
555
          $entity->revision = TRUE;
556
          // Without this cache clear entity_revision_is_default will
557
          // incorrectly return false here when creating a new published revision
558
          if (!isset($cleared_host_entity_cache)) {
559
            list($entity_id) = entity_extract_ids($host_entity_type, $host_entity);
560
            entity_get_controller($host_entity_type)->resetCache(array($entity_id));
561
            $cleared_host_entity_cache = TRUE;
562
          }
563
          $is_default = entity_revision_is_default($host_entity_type, $host_entity);
564
          // If an entity type does not support saving non-default entities,
565
          // assume it will be saved as default.
566
          if (!isset($is_default) || $is_default) {
567
            $entity->default_revision = TRUE;
568
            $entity->archived = FALSE;
569
          }
570
          else {
571
            $entity->default_revision = FALSE;
572
          }
573
        }
574

    
575
        if (!empty($entity->is_new)) {
576
          $entity->setHostEntity($host_entity_type, $host_entity, $langcode, FALSE);
577
        }
578
        else {
579
          $entity->updateHostEntity($host_entity, $host_entity_type);
580
        }
581

    
582
        $entity->save(TRUE);
583

    
584
        $item = array(
585
          'value' => $entity->item_id,
586
          'revision_id' => $entity->revision_id,
587
        );
588
      }
589
    }
590

    
591
    unset($original_by_id[$item['value']]);
592
  }
593

    
594
  // If there are removed items, care about deleting the item entities.
595
  if ($original_by_id) {
596
    $ids = array_flip($original_by_id);
597

    
598
    // If we are creating a new revision, the old-items should be kept but get
599
    // marked as archived now.
600
    if (!empty($host_entity->revision)) {
601
      db_update('field_collection_item')
602
        ->fields(array('archived' => 1))
603
        ->condition('item_id', $ids, 'IN')
604
        ->execute();
605
    }
606
    else {
607
      // Load items from the original entity from all languages checking which
608
      // are the unused items.
609
      $current_items = array();
610
      $languages = language_list();
611
      foreach ($languages as $langcode_value) {
612
        $current_items += !empty($host_entity->{$field['field_name']}[$langcode_value->language]) ? $host_entity->{$field['field_name']}[$langcode_value->language] : array();
613
        $current_by_id = field_collection_field_item_to_ids($current_items);
614
      }
615
      $items_to_remove = array_diff($ids, $current_by_id);
616
      // Delete unused field collection items now.
617
      foreach (field_collection_item_load_multiple($items_to_remove) as $un_item) {
618
        $un_item->updateHostEntity($host_entity);
619
        $un_item->deleteRevision(TRUE);
620
      }
621
    }
622
  }
623
}
624

    
625
/**
626
 * Implements hook_field_delete().
627
 */
628
function field_collection_field_delete($entity_type, $entity, $field, $instance, $langcode, &$items) {
629
  // Also delete all embedded entities.
630
  if ($ids = field_collection_field_item_to_ids($items)) {
631
    // We filter out entities that are still being referenced by other
632
    // host-entities. This should never be the case, but it might happened e.g.
633
    // when modules cloned a node without knowing about field-collection.
634
    $entity_info = entity_get_info($entity_type);
635
    $entity_id_name = $entity_info['entity keys']['id'];
636
    $field_column = key($field['columns']);
637

    
638
    foreach ($ids as $id_key => $id) {
639
      $query = new EntityFieldQuery();
640
      $entities = $query
641
        ->fieldCondition($field['field_name'], $field_column, $id)
642
        ->execute();
643
      unset($entities[$entity_type][$entity->$entity_id_name]);
644

    
645
      if (!empty($entities[$entity_type])) {
646
        // Filter this $id out.
647
        unset($ids[$id_key]);
648
      }
649

    
650
      // Set a flag to remember that the host entity is being deleted. See
651
      // FieldCollectionItemEntity::deleteHostEntityReference().
652
      // Doing this on $entity is not sufficient because the cache for $entity
653
      // may have been reset since it was loaded.  That would cause
654
      // hostEntity() to load it from the database later without the flag.
655
      $field_collection_item = field_collection_item_load($id);
656
      if ($field_collection_item) {
657
        $hostEntity = $field_collection_item->hostEntity();
658
        if (!empty($hostEntity)) {
659
          $hostEntity->field_collection_deleting = TRUE;
660
        }
661
      }
662
    }
663

    
664
    entity_delete_multiple('field_collection_item', $ids);
665
  }
666
}
667

    
668
/**
669
 * Implements hook_field_delete_revision().
670
 */
671
function field_collection_field_delete_revision($entity_type, $entity, $field, $instance, $langcode, &$items) {
672
  foreach ($items as $item) {
673
    if (!empty($item['revision_id'])) {
674
      if ($entity = field_collection_item_revision_load($item['revision_id'])) {
675
        $entity->deleteRevision(TRUE);
676
      }
677
    }
678
  }
679
}
680

    
681
/**
682
 * Get an array of field collection item IDs stored in the given field items.
683
 */
684
function field_collection_field_item_to_ids($items) {
685
  $ids = array();
686
  foreach ($items as $item) {
687
    if (!empty($item['value'])) {
688
      $ids[] = $item['value'];
689
    }
690
  }
691
  return $ids;
692
}
693

    
694
/**
695
 * Implements hook_field_is_empty().
696
 */
697
function field_collection_field_is_empty($item, $field) {
698
  if (!empty($item['value'])) {
699
    return FALSE;
700
  }
701
  elseif (isset($item['entity'])) {
702
    return field_collection_item_is_empty($item['entity']);
703
  }
704
  return TRUE;
705
}
706

    
707
/**
708
 * Determines whether a field collection item entity is empty based on the collection-fields.
709
 */
710
function field_collection_item_is_empty(FieldCollectionItemEntity $item) {
711
  $instances = field_info_instances('field_collection_item', $item->field_name);
712
  $is_empty = TRUE;
713

    
714
  // Check whether all fields are booleans.
715
  $all_boolean = $instances && !(bool) array_filter($instances, '_field_collection_field_is_not_boolean');
716

    
717
  foreach ($instances as $instance) {
718
    $field_name = $instance['field_name'];
719
    $field = field_info_field($field_name);
720

    
721
    // Boolean fields as those are always considered non-empty, thus their
722
    // information is not useful and can be skipped by default.
723
    if (!$all_boolean && $field['type'] == 'list_boolean') {
724
      continue;
725
    }
726

    
727
    // Determine the list of languages to iterate on.
728
    $languages = field_available_languages('field_collection_item', $field);
729

    
730
    foreach ($languages as $langcode) {
731
      if (!empty($item->{$field_name}[$langcode])) {
732
        // If at least one collection-field is not empty; the
733
        // field collection item is not empty.
734
        foreach ($item->{$field_name}[$langcode] as $field_item) {
735
          if (!module_invoke($field['module'], 'field_is_empty', $field_item, $field)) {
736
            $is_empty = FALSE;
737
          }
738
        }
739
      }
740
    }
741
  }
742

    
743
  // Allow other modules a chance to alter the value before returning.
744
  drupal_alter('field_collection_is_empty', $is_empty, $item);
745
  return $is_empty;
746
}
747

    
748
/**
749
 * Callback used by array_filter in field_collection_is_empty.
750
 */
751
function _field_collection_field_is_not_boolean($instance) {
752
  $field = field_info_field($instance['field_name']);
753
  return $field['type'] != 'list_boolean';
754
}
755

    
756
/**
757
 * Implements hook_field_formatter_info().
758
 */
759
function field_collection_field_formatter_info() {
760
  return array(
761
    'field_collection_list' => array(
762
      'label' => t('Links to field collection items'),
763
      'field types' => array('field_collection'),
764
      'settings' => array(
765
        'edit' => t('Edit'),
766
        'translate' => t('Translate'),
767
        'delete' => t('Delete'),
768
        'add' => t('Add'),
769
        'description' => TRUE,
770
      ),
771
    ),
772
    'field_collection_view' => array(
773
      'label' => t('Field collection items'),
774
      'field types' => array('field_collection'),
775
      'settings' => array(
776
        'edit' => t('Edit'),
777
        'translate' => t('Translate'),
778
        'delete' => t('Delete'),
779
        'add' => t('Add'),
780
        'description' => TRUE,
781
        'view_mode' => 'full',
782
      ),
783
    ),
784
    'field_collection_fields' => array(
785
      'label' => t('Fields only'),
786
      'field types' => array('field_collection'),
787
      'settings' => array(
788
        'view_mode' => 'full',
789
      ),
790
    ),
791
  );
792
}
793

    
794
/**
795
 * Implements hook_field_formatter_settings_form().
796
 */
797
function field_collection_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
798
  $display = $instance['display'][$view_mode];
799
  $settings = $display['settings'];
800
  $elements = array();
801

    
802
  if ($display['type'] != 'field_collection_fields') {
803
    $elements['add'] = array(
804
      '#type' => 'textfield',
805
      '#title' => t('Add link title'),
806
      '#default_value' => $settings['add'],
807
      '#description' => t('Leave the title empty, to hide the link.'),
808
    );
809
    $elements['edit'] = array(
810
      '#type' => 'textfield',
811
      '#title' => t('Edit link title'),
812
      '#default_value' => $settings['edit'],
813
      '#description' => t('Leave the title empty, to hide the link.'),
814
    );
815
    $elements['translate'] = array(
816
      '#type' => 'textfield',
817
      '#title' => t('Translate link title'),
818
      '#default_value' => isset($settings['translate']) ? $settings['translate'] : '',
819
      '#description' => t('Leave the title empty, to hide the link.'),
820
      '#access' => field_collection_item_is_translatable(),
821
    );
822
    $elements['delete'] = array(
823
      '#type' => 'textfield',
824
      '#title' => t('Delete link title'),
825
      '#default_value' => $settings['delete'],
826
      '#description' => t('Leave the title empty, to hide the link.'),
827
    );
828
    $elements['description'] = array(
829
      '#type' => 'checkbox',
830
      '#title' => t('Show the field description beside the add link.'),
831
      '#default_value' => $settings['description'],
832
      '#description' => t('If enabled and the add link is shown, the field description is shown in front of the add link.'),
833
    );
834
  }
835

    
836
  // Add a select form element for view_mode if viewing the rendered field_collection.
837
  if ($display['type'] !== 'field_collection_list') {
838

    
839
    $entity_type = entity_get_info('field_collection_item');
840
    $options = array();
841
    foreach ($entity_type['view modes'] as $mode => $info) {
842
      $options[$mode] = $info['label'];
843
    }
844

    
845
    $elements['view_mode'] = array(
846
      '#type' => 'select',
847
      '#title' => t('View mode'),
848
      '#options' => $options,
849
      '#default_value' => $settings['view_mode'],
850
      '#description' => t('Select the view mode'),
851
    );
852
  }
853

    
854
  return $elements;
855
}
856

    
857
/**
858
 * Implements hook_field_formatter_settings_summary().
859
 */
860
function field_collection_field_formatter_settings_summary($field, $instance, $view_mode) {
861
  $display = $instance['display'][$view_mode];
862
  $settings = $display['settings'];
863
  $output = array();
864

    
865
  if ($display['type'] !== 'field_collection_fields') {
866
    $links = field_collection_get_operations($settings, TRUE);
867
    if ($links) {
868
      $output[] = t('Links: @links', array('@links' => check_plain(implode(', ', $links))));
869
    }
870
    else {
871
      $output[] = t('Links: none');
872
    }
873
  }
874

    
875
  if ($display['type'] !== 'field_collection_list') {
876
    $entity_type = entity_get_info('field_collection_item');
877
    if (!empty($entity_type['view modes'][$settings['view_mode']]['label'])) {
878
      $output[] = t('View mode: @mode', array('@mode' => $entity_type['view modes'][$settings['view_mode']]['label']));
879
    }
880
  }
881

    
882
  return implode('<br>', $output);
883
}
884

    
885
/**
886
 * Implements hook_field_formatter_view().
887
 */
888
function field_collection_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
889
  $element = array();
890
  $settings = $display['settings'];
891

    
892
  switch ($display['type']) {
893
    case 'field_collection_list':
894

    
895
      foreach ($items as $delta => $item) {
896
        if ($field_collection = field_collection_field_get_entity($item)) {
897
          $output = l($field_collection->label(), $field_collection->path());
898
          $links = array();
899
          foreach (field_collection_get_operations($settings) as $op => $label) {
900
            if ($settings[$op] && entity_access($op == 'edit' ? 'update' : $op, 'field_collection_item', $field_collection)) {
901
              $title = entity_i18n_string("field:{$field['field_name']}:{$instance['bundle']}:setting_$op", $settings[$op]);
902
              $links[] = l($title, $field_collection->path() . '/' . $op, array('query' => drupal_get_destination()));
903
            }
904
          }
905
          if ($links) {
906
            $output .= ' (' . implode('|', $links) . ')';
907
          }
908
          $element[$delta] = array('#markup' => $output);
909
        }
910
      }
911
      field_collection_field_formatter_links($element, $entity_type, $entity, $field, $instance, $langcode, $items, $display);
912
      break;
913

    
914
    case 'field_collection_view':
915

    
916
      $view_mode = !empty($display['settings']['view_mode']) ? $display['settings']['view_mode'] : 'full';
917
      foreach ($items as $delta => $item) {
918
        if ($field_collection = field_collection_field_get_entity($item)) {
919
          $element[$delta]['entity'] = $field_collection->view($view_mode, $langcode);
920
          $element[$delta]['#theme_wrappers'] = array('field_collection_view');
921
          $element[$delta]['#attributes']['class'][] = 'field-collection-view';
922
          $element[$delta]['#attributes']['class'][] = 'clearfix';
923
          $element[$delta]['#attributes']['class'][] = drupal_clean_css_identifier('view-mode-' . $view_mode);
924

    
925
          $links = array(
926
            '#theme' => 'links__field_collection_view',
927
          );
928
          $links['#attributes']['class'][] = 'field-collection-view-links';
929
          foreach (field_collection_get_operations($settings) as $op => $label) {
930
            if ($settings[$op] && entity_access($op == 'edit' ? 'update' : $op, 'field_collection_item', $field_collection)) {
931
              $links['#links'][$op] = array(
932
                'title' => entity_i18n_string("field:{$field['field_name']}:{$instance['bundle']}:setting_$op", $settings[$op]),
933
                'href' => $field_collection->path() . '/' . $op,
934
                'query' => drupal_get_destination(),
935
              );
936
            }
937
          }
938
          $element[$delta]['links'] = $links;
939
        }
940
      }
941
      field_collection_field_formatter_links($element, $entity_type, $entity, $field, $instance, $langcode, $items, $display);
942
      if (!empty($items) || !empty($element['#suffix'])) {
943
        $element['#attached']['css'][] = drupal_get_path('module', 'field_collection') . '/field_collection.theme.css';
944
      }
945
      break;
946

    
947
    case 'field_collection_fields':
948

    
949
      $view_mode = !empty($display['settings']['view_mode']) ? $display['settings']['view_mode'] : 'full';
950
      foreach ($items as $delta => $item) {
951
        if ($field_collection = field_collection_field_get_entity($item)) {
952
          $element[$delta]['entity'] = $field_collection->view($view_mode, $langcode);
953
        }
954
      }
955
      break;
956
  }
957

    
958
  return $element;
959
}
960

    
961
/**
962
 * Returns an array of enabled operations.
963
 */
964
function field_collection_get_operations($settings, $add = FALSE) {
965
  $operations = array();
966

    
967
  if ($add) {
968
    $operations[] = 'add';
969
  }
970
  $operations[] = 'edit';
971
  if (field_collection_item_is_translatable()) {
972
    $operations[] = 'translate';
973
  }
974
  $operations[] = 'delete';
975

    
976
  global $field_collection_operation_keys;
977
  $field_collection_operation_keys = array_flip($operations);
978
  $operations = array_filter(array_intersect_key($settings, $field_collection_operation_keys));
979
  asort($operations);
980

    
981
  return $operations;
982
}
983

    
984
/**
985
 * Helper function to add links to a field collection field.
986
 */
987
function field_collection_field_formatter_links(&$element, $entity_type, $entity, $field, $instance, $langcode, $items, $display) {
988
  $settings = $display['settings'];
989
  $allow_create_item = FALSE;
990

    
991
  if ($settings['add'] && ($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED || count($items) < $field['cardinality'])) {
992
    // Check whether the current is allowed to create a new item.
993
    $field_collection_item = entity_create('field_collection_item', array('field_name' => $field['field_name']));
994
    $field_collection_item->setHostEntity($entity_type, $entity, $langcode, FALSE);
995

    
996
    if (entity_access('create', 'field_collection_item', $field_collection_item)) {
997
      $allow_create_item = TRUE;
998
      $path = field_collection_field_get_path($field);
999
      list($id) = entity_extract_ids($entity_type, $entity);
1000
      $element['#suffix'] = '';
1001
      if (!empty($settings['description']) && $entity_type != 'node') {
1002
        $element['#suffix'] .= '<div class="description field-collection-description">' . field_filter_xss($instance['description']) . '</div>';
1003
      }
1004
      $title = entity_i18n_string("field:{$field['field_name']}:{$instance['bundle']}:setting_add", $settings['add']);
1005
      $add_path = $path . '/add/' . $entity_type . '/' . $id;
1006
      $element['#suffix'] .= '<ul class="action-links action-links-field-collection-add"><li>';
1007
      $element['#suffix'] .= l($title, $add_path, array('query' => drupal_get_destination()));
1008
      $element['#suffix'] .= '</li></ul>';
1009
    }
1010
  }
1011
  // If there is no add link, add a special class to the last item.
1012
  if (!empty($items) || $allow_create_item) {
1013
    if (empty($element['#suffix'])) {
1014
      $index = count(element_children($element)) - 1;
1015
      $element[$index]['#attributes']['class'][] = 'field-collection-view-final';
1016
    }
1017

    
1018
    $element += array('#prefix' => '', '#suffix' => '');
1019
    $element['#prefix'] .= '<div class="field-collection-container clearfix">';
1020
    $element['#suffix'] .= '</div>';
1021
  }
1022

    
1023
  return $element;
1024
}
1025

    
1026
/**
1027
 * Themes field collection items printed using the field_collection_view formatter.
1028
 */
1029
function theme_field_collection_view($variables) {
1030
  $element = $variables['element'];
1031
  return '<div' . drupal_attributes($element['#attributes']) . '>' . $element['#children'] . '</div>';
1032
}
1033

    
1034
/**
1035
 * Implements hook_field_widget_info().
1036
 */
1037
function field_collection_field_widget_info() {
1038
  return array(
1039
    'field_collection_hidden' => array(
1040
      'label' => t('Hidden'),
1041
      'field types' => array('field_collection'),
1042
      'behaviors' => array(
1043
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
1044
        'default value' => FIELD_BEHAVIOR_NONE,
1045
      ),
1046
    ),
1047
    'field_collection_embed' => array(
1048
      'label' => t('Embedded'),
1049
      'field types' => array('field_collection'),
1050
      'behaviors' => array(
1051
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
1052
        'default value' => FIELD_BEHAVIOR_NONE,
1053
      ),
1054
    ),
1055
  );
1056
}
1057

    
1058
/**
1059
 * Implements hook_field_widget_form().
1060
 */
1061
function field_collection_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
1062
  static $recursion = 0;
1063

    
1064
  switch ($instance['widget']['type']) {
1065
    case 'field_collection_hidden':
1066
      return $element;
1067

    
1068
    case 'field_collection_embed':
1069
      // If the field collection item form contains another field collection,
1070
      // we might ran into a recursive loop. Prevent that.
1071
      if ($recursion++ > 3) {
1072
        drupal_set_message(t('The field collection item form has not been embedded to avoid recursive loops.'), 'error');
1073
        return $element;
1074
      }
1075
      $field_parents = $element['#field_parents'];
1076
      $field_name = $element['#field_name'];
1077
      $language = $element['#language'];
1078

    
1079
      // Nest the field collection item entity form in a dedicated parent space,
1080
      // by appending [field_name, langcode, delta] to the current parent space.
1081
      // That way the form values of the field collection item are separated.
1082
      $parents = array_merge($field_parents, array($field_name, $language, $delta));
1083

    
1084
      $element += array(
1085
        '#element_validate' => array('field_collection_field_widget_embed_validate'),
1086
        '#parents' => $parents,
1087
      );
1088

    
1089
      if ($field['cardinality'] == 1) {
1090
        $element['#type'] = 'fieldset';
1091
      }
1092

    
1093
      $field_state = field_form_get_state($field_parents, $field_name, $language, $form_state);
1094

    
1095
      if (field_collection_hide_blank_items($field) && $delta == $field_state['items_count'] && $delta > 0) {
1096
        // Do not add a blank item. Also see
1097
        // field_collection_field_attach_form() for correcting #max_delta.
1098
        $recursion--;
1099
        return FALSE;
1100
      }
1101
      elseif (field_collection_hide_blank_items($field) && $field_state['items_count'] == 0) {
1102
        // We show one item, so also specify that as item count. So when the
1103
        // add button is pressed the item count will be 2 and we show two items.
1104
        $field_state['items_count'] = 1;
1105
      }
1106

    
1107
      if (isset($field_state['entity'][$delta])) {
1108
        $field_collection_item = $field_state['entity'][$delta];
1109
      }
1110
      else {
1111
        if (isset($items[$delta])) {
1112
          $field_collection_item = field_collection_field_get_entity($items[$delta], $field_name);
1113
        }
1114
        // Show an empty collection if we have no existing one or it does not
1115
        // load.
1116
        if (empty($field_collection_item)) {
1117
          $field_collection_item = entity_create('field_collection_item', array('field_name' => $field_name));
1118
          $field_collection_item->setHostEntity($element['#entity_type'], $element['#entity'], $langcode);
1119
        }
1120

    
1121
        // Put our entity in the form state, so FAPI callbacks can access it.
1122
        $field_state['entity'][$delta] = $field_collection_item;
1123
      }
1124

    
1125
      // Register a child entity translation handler to properly deal with the
1126
      // entity form language.
1127
      if (field_collection_item_is_translatable()) {
1128
        $element['#host_entity_type'] = $element['#entity_type'];
1129
        $element['#host_entity'] = $element['#entity'];
1130
        // Give each field collection item a unique entity translation handler
1131
        // ID, otherwise an infinite loop occurs when adding values to nested
1132
        // field collection items.
1133
        if (!isset($field_collection_item->entity_translation_handler_id)) {
1134
          list($id, $revision_id) = entity_extract_ids('field_collection_item', $field_collection_item);
1135
          $revision_id = isset($revision_id) ? $revision_id : 0;
1136
          $field_collection_item->entity_translation_handler_id = 'field_collection_item' . '-' . (!empty($id) ? 'eid-' . $id . '-' . $revision_id : 'new-' . rand());
1137
        }
1138
        $element['#field_collection_item'] = $field_collection_item;
1139
        field_collection_add_child_translation_handler($element);
1140
        // Ensure this is executed even with cached forms. This is mainly useful
1141
        // when dealing with AJAX calls.
1142
        $element['#process'][] = 'field_collection_add_child_translation_handler';
1143
        // Flag the field to be processed in field_collection_form_alter to
1144
        // avoid adding incorrect translation hints.
1145
        $address = array_slice($element['#parents'], 0, -2);
1146
        if (empty($form['#field_collection_translation_fields']) || !in_array($address, $form['#field_collection_translation_fields'])) {
1147
          $form['#field_collection_translation_fields'][] = $address;
1148
        }
1149
      }
1150

    
1151
      // Add the subform
1152
      field_form_set_state($field_parents, $field_name, $language, $form_state, $field_state);
1153
      // Set the language to to parent entity language, because
1154
      // field_content_languages() will always set $language to LANGUAGE_NONE.
1155
      if (field_collection_item_is_translatable()) {
1156
        field_attach_form('field_collection_item', $field_collection_item, $element, $form_state, entity_language($element['#host_entity_type'], $element['#host_entity']));
1157
      }
1158
      else {
1159
        field_attach_form('field_collection_item', $field_collection_item, $element, $form_state, $language);
1160
      }
1161

    
1162
      // Make sure subfields get translatable clues (like 'all languages')
1163
      if (field_collection_item_is_translatable() && variable_get('entity_translation_shared_labels', TRUE)) {
1164
        foreach (element_children($element) as $key) {
1165
          $element[$key]['#process'][] = 'entity_translation_element_translatability_clue';
1166
        }
1167
      }
1168

    
1169
      if (empty($element['#required'])) {
1170
        $element['#after_build'][] = 'field_collection_field_widget_embed_delay_required_validation';
1171
      }
1172

    
1173
      if ($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED && empty($form_state['programmed'])) {
1174
        $element['remove_button'] = array(
1175
          '#delta' => $delta,
1176
          '#name' => implode('_', $parents) . '_remove_button',
1177
          '#type' => 'submit',
1178
          '#value' => t('Remove'),
1179
          '#validate' => array(),
1180
          '#submit' => array('field_collection_remove_submit'),
1181
          '#attributes' => array('class' => array('remove-button')),
1182
          '#limit_validation_errors' => array(),
1183
          '#ajax' => array(
1184
            // 'wrapper' is filled in field_collection_field_attach_form().
1185
            'callback' => 'field_collection_remove_js',
1186
            'effect' => 'fade',
1187
          ),
1188
          '#weight' => 1000,
1189
        );
1190
      }
1191

    
1192
      $recursion--;
1193
      return $element;
1194
  }
1195
}
1196

    
1197
/**
1198
 * Implements hook_entity_translation_source_field_state_alter()
1199
 */
1200
function field_collection_entity_translation_source_field_state_alter(&$field_state) {
1201
  if (isset($field_state['entity'])) {
1202
    module_load_include('inc', 'entity', 'includes/entity.ui');
1203
    foreach ($field_state['entity'] as $delta => $entity) {
1204
      if ($entity instanceof FieldCollectionItemEntity) {
1205
        $field_state['entity'][$delta] = entity_ui_clone_entity('field_collection_item', $entity);
1206
      }
1207
    }
1208
  }
1209
}
1210

    
1211
/**
1212
 * Registers a child entity translation handler for the given element.
1213
 */
1214
function field_collection_add_child_translation_handler($element) {
1215
  $handler = entity_translation_get_handler($element['#host_entity_type'], $element['#host_entity']);
1216
  $handler->addChild('field_collection_item', $element['#field_collection_item']);
1217
  return $element;
1218
}
1219

    
1220
/**
1221
 * Implements hook_field_attach_form().
1222
 *
1223
 * Corrects #max_delta when we hide the blank field collection item.
1224
 *
1225
 * @see field_add_more_js()
1226
 * @see field_collection_field_widget_form()
1227
 */
1228
function field_collection_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
1229

    
1230
  foreach (field_info_instances($entity_type, $form['#bundle']) as $field_name => $instance) {
1231
    $field = field_info_field($field_name);
1232

    
1233
    if ($field['type'] == 'field_collection' && field_collection_hide_blank_items($field)
1234
        && field_access('edit', $field, $entity_type) && $instance['widget']['type'] == 'field_collection_embed') {
1235

    
1236
      $element_langcode = $form[$field_name]['#language'];
1237
      if ($form[$field_name][$element_langcode]['#max_delta'] > 0) {
1238
        $form[$field_name][$element_langcode]['#max_delta']--;
1239
      }
1240
      // Remove blank form elements and force user to explicitly add a field
1241
      // collection if both 'hide_initial_item' and 'hide_blank_items' are TRUE.
1242
      if ($field['settings']['hide_initial_item']
1243
          && $field['settings']['hide_blank_items']
1244
          && field_collection_item_is_empty($form[$field_name][$element_langcode][0]['#entity'])) {
1245

    
1246
        _field_collection_process_children_attached($form[$field_name][$element_langcode][0]);
1247
        unset($form[$field_name][$element_langcode][0]);
1248
        unset($form_state['field']['#parents'][$field_name][$element_langcode][0]);
1249
      }
1250
    }
1251

    
1252
    if ($field['type'] == 'field_collection'
1253
        && $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED
1254
        && empty($form_state['programmed'])
1255
        && field_access('edit', $field, $entity_type)
1256
        && $instance['widget']['type'] == 'field_collection_embed') {
1257

    
1258
      $element_langcode = $form[$field_name]['#language'];
1259
      $element_wrapper = $form[$field_name][$element_langcode]['add_more']['#ajax']['wrapper'];
1260
      for ($i = 0; $i <= $form[$field_name][$element_langcode]['#max_delta']; $i++) {
1261
        if (isset($form[$field_name][$element_langcode][$i]['remove_button'])) {
1262
          $form[$field_name][$element_langcode][$i]['remove_button']['#ajax']['wrapper'] = $element_wrapper;
1263
        }
1264
      }
1265
    }
1266
  }
1267

    
1268
  // If FCs are translatable, make sure we mark any necessary sub-fields in the
1269
  // FC widget as translatable as well.
1270
  if ($entity_type == 'field_collection_item'
1271
      && field_collection_item_is_translatable()
1272
  ) {
1273
    foreach (field_info_instances($entity_type, $form['#bundle']) as $field_name => $instance) {
1274
      $field = field_info_field($field_name);
1275
      if (isset($field['translatable'])) {
1276
        $form[$field_name]['#multilingual'] = (boolean) $field['translatable'];
1277
      }
1278
    }
1279
  }
1280
}
1281

    
1282
/**
1283
 * Recurses through field children and processes thier attachments.
1284
 */
1285
function _field_collection_process_children_attached($elements) {
1286
  if (empty($elements)) {
1287
    return;
1288
  }
1289

    
1290
  if (isset($elements['#attached'])) {
1291
    drupal_process_attached($elements);
1292
  }
1293

    
1294
  foreach (element_children($elements) as $key) {
1295
    _field_collection_process_children_attached($elements[$key]);
1296
  }
1297
}
1298

    
1299
/**
1300
 * AJAX callback for removing a field collection item.
1301
 *
1302
 * This returns the new page content to replace the page content made obsolete
1303
 * by the form submission.
1304
 *
1305
 * @see field_collection_remove_submit()
1306
 */
1307
function field_collection_remove_js($form, $form_state) {
1308
  $button = $form_state['triggering_element'];
1309

    
1310
  // Go one level up in the form, to the widgets container.
1311
  $element = drupal_array_get_nested_value($form, array_slice($button['#array_parents'], 0, -2));
1312
  $field_name = $element['#field_name'];
1313
  $langcode = $element['#language'];
1314
  $parents = $element['#field_parents'];
1315

    
1316
  $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
1317

    
1318
  $field = $field_state['field'];
1319
  if ($field['cardinality'] != FIELD_CARDINALITY_UNLIMITED) {
1320
    return;
1321
  }
1322

    
1323
  return $element;
1324
}
1325

    
1326
/**
1327
 * Submit callback to remove an item from the field UI multiple wrapper.
1328
 *
1329
 * When a remove button is submitted, we need to find the item that it
1330
 * referenced and delete it. Since field UI has the deltas as a straight
1331
 * unbroken array key, we have to renumber everything down. Since we do this
1332
 * we *also* need to move all the deltas around in the $form_state['values'],
1333
 * $form_state['input'], and $form_state['field'] so that user changed values
1334
 * follow. This is a bit of a complicated process.
1335
 */
1336
function field_collection_remove_submit($form, &$form_state) {
1337
  $button = $form_state['triggering_element'];
1338
  $delta = $button['#delta'];
1339

    
1340
  // Where in the form we'll find the parent element.
1341
  $address = array_slice($button['#array_parents'], 0, -2);
1342
  $values_address = array_slice($button['#parents'], 0, -2);
1343

    
1344
  // Go one level up in the form, to the widgets container.
1345
  $parent_element = drupal_array_get_nested_value($form, $address);
1346
  $field_name = $parent_element['#field_name'];
1347
  $langcode = $parent_element['#language'];
1348
  $parents = $parent_element['#field_parents'];
1349

    
1350
  $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
1351

    
1352
  // Use the actual array of field collection items as the upper limit of this
1353
  // for loop rather than 'item_count'. This is because it will be creating extra
1354
  // dummy items here and the two measures go out of sync after the fist delete.
1355
  $field_collection_item_count = count($field_state['entity']) - 1;
1356

    
1357
  // Go ahead and renumber everything from our delta to the last
1358
  // item down one. This will overwrite the item being removed.
1359
  for ($i = $delta; $i <= $field_collection_item_count; $i++) {
1360
    $old_element_address = array_merge($address, array($i + 1));
1361
    $old_element_values_address = array_merge($values_address, array($i + 1));
1362
    $new_element_values_address = array_merge($values_address, array($i));
1363

    
1364
    $moving_element = drupal_array_get_nested_value($form, $old_element_address);
1365
    $moving_element_value = drupal_array_get_nested_value($form_state['values'], $old_element_values_address);
1366
    $moving_element_input = drupal_array_get_nested_value($form_state['input'], $old_element_values_address);
1367
    $moving_element_field = drupal_array_get_nested_value($form_state['field']['#parents'], $old_element_address);
1368

    
1369
    // Tell the element where it's being moved to.
1370
    $moving_element['#parents'] = $new_element_values_address;
1371

    
1372
    // Move the element around.
1373
    form_set_value($moving_element, $moving_element_value, $form_state);
1374
    drupal_array_set_nested_value($form_state['input'], $moving_element['#parents'], $moving_element_input);
1375
    drupal_array_set_nested_value($form_state['field']['#parents'], $moving_element['#parents'], $moving_element_field);
1376

    
1377
    // Move the entity in our saved state.
1378
    if (isset($field_state['entity'][$i + 1])) {
1379
      $field_state['entity'][$i] = $field_state['entity'][$i + 1];
1380
    }
1381
    else {
1382
      unset($field_state['entity'][$i]);
1383
    }
1384
  }
1385

    
1386
  // Replace the deleted entity with an empty one. This helps to ensure that
1387
  // trying to add a new entity won't ressurect a deleted entity from the
1388
  // trash bin.
1389
  $count = count($field_state['entity']);
1390
  $field_state['entity'][$count] = entity_create('field_collection_item', array('field_name' => $field_name));
1391

    
1392
  // Then remove the last item. But we must not go negative.
1393
  if ($field_state['items_count'] > 0) {
1394
    $field_state['items_count']--;
1395
  }
1396

    
1397
  // Fix the weights. Field UI lets the weights be in a range of
1398
  // (-1 * item_count) to (item_count). This means that when we remove one,
1399
  // the range shrinks; weights outside of that range then get set to
1400
  // the first item in the select by the browser, floating them to the top.
1401
  // We use a brute force method because we lost weights on both ends
1402
  // and if the user has moved things around, we have to cascade because
1403
  // if I have items weight weights 3 and 4, and I change 4 to 3 but leave
1404
  // the 3, the order of the two 3s now is undefined and may not match what
1405
  // the user had selected.
1406
  $input = drupal_array_get_nested_value($form_state['input'], $values_address);
1407
  // Sort by weight
1408
  uasort($input, '_field_sort_items_helper');
1409

    
1410
  // Reweight everything in the correct order.
1411
  $weight = -1 * $field_state['items_count'];
1412
  foreach ($input as $key => $item) {
1413
    if ($item) {
1414
      $input[$key]['_weight'] = $weight++;
1415
    }
1416
  }
1417

    
1418
  drupal_array_set_nested_value($form_state['input'], $values_address, $input);
1419
  field_form_set_state($parents, $field_name, $langcode, $form_state, $field_state);
1420

    
1421
  $form_state['rebuild'] = TRUE;
1422
}
1423

    
1424
/**
1425
 * Gets a field collection item entity for a given field item.
1426
 *
1427
 * @param $field_name
1428
 *   (optional) If given and there is no entity yet, a new entity object is
1429
 *   created for the given item.
1430
 *
1431
 * @return
1432
 *   The entity object or FALSE.
1433
 */
1434
function field_collection_field_get_entity(&$item, $field_name = NULL) {
1435
  if (isset($item['entity']) && ($item['entity']->entityType() == 'field_collection_item')) {
1436
    return $item['entity'];
1437
  }
1438
  elseif (isset($item['value'])) {
1439
    // By default always load the default revision, so caches get used.
1440
    $entity = field_collection_item_load($item['value']);
1441
    if ($entity && $entity->revision_id != $item['revision_id']) {
1442
      // A non-default revision is a referenced, so load this one.
1443
      $entity = field_collection_item_revision_load($item['revision_id']);
1444
    }
1445
    return $entity;
1446
  }
1447
  elseif (!isset($item['entity']) && isset($field_name)) {
1448
    $item['entity'] = entity_create('field_collection_item', array('field_name' => $field_name));
1449
    return $item['entity'];
1450
  }
1451
  return FALSE;
1452
}
1453

    
1454
/**
1455
 * FAPI #after_build of an individual field collection element to delay the validation of #required.
1456
 */
1457
function field_collection_field_widget_embed_delay_required_validation(&$element, &$form_state) {
1458
  // If the process_input flag is set, the form and its input is going to be
1459
  // validated. Prevent #required (sub)fields from throwing errors while
1460
  // their non-#required field collection item is empty.
1461
  if ($form_state['process_input']) {
1462
    _field_collection_collect_required_elements($element, $element['#field_collection_required_elements']);
1463
  }
1464
  return $element;
1465
}
1466

    
1467
function _field_collection_collect_required_elements(&$element, &$required_elements) {
1468
  // Recurse through all children.
1469
  foreach (element_children($element) as $key) {
1470
    if (isset($element[$key]) && $element[$key]) {
1471
      _field_collection_collect_required_elements($element[$key], $required_elements);
1472
    }
1473
  }
1474
  if (!empty($element['#required'])) {
1475
    $element['#required'] = FALSE;
1476
    $required_elements[] = &$element;
1477
    $element += array('#pre_render' => array());
1478
    array_unshift($element['#pre_render'], 'field_collection_field_widget_render_required');
1479
  }
1480
}
1481

    
1482
/**
1483
 * #pre_render callback that ensures the element is rendered as being required.
1484
 */
1485
function field_collection_field_widget_render_required($element) {
1486
  $element['#required'] = TRUE;
1487
  return $element;
1488
}
1489

    
1490
/**
1491
 * FAPI validation of an individual field collection element.
1492
 */
1493
function field_collection_field_widget_embed_validate($element, &$form_state, $complete_form) {
1494
  $field = field_widget_field($element, $form_state);
1495
  $field_parents = $element['#field_parents'];
1496
  $field_name = $element['#field_name'];
1497
  $language = $element['#language'];
1498

    
1499
  $field_state = field_form_get_state($field_parents, $field_name, $language, $form_state);
1500

    
1501
  // We have to populate the field_collection_item before we can attach it to
1502
  // the form.
1503
  if (isset($field_state['entity'][$element['#delta']])) {
1504
    $field_collection_item = $field_state['entity'][$element['#delta']];
1505
  }
1506
  else {
1507
    $field_values = drupal_array_get_nested_value($form_state['values'], $field_state['array_parents']);
1508
    if ($field_values[$element['#delta']]) {
1509
      $field_collection_item = entity_create('field_collection_item', array('field_name' => $field['field_name']));
1510
      foreach ($field_values[$element['#delta']] as $key => $value) {
1511
        if (property_exists($field_collection_item, $key)) {
1512
          $field_collection_item->{$key} = $value;
1513
        }
1514
      }
1515
    }
1516
  }
1517

    
1518
  // Attach field API validation of the embedded form.
1519
  field_attach_form_validate('field_collection_item', $field_collection_item, $element, $form_state);
1520

    
1521
  // Handle a possible language change.
1522
  if (field_collection_item_is_translatable()) {
1523
    $handler = entity_translation_get_handler('field_collection_item', $field_collection_item);
1524
    $element_values = &drupal_array_get_nested_value($form_state['values'], $field_state['array_parents']);
1525
    $element_form_state = array('values' => &$element_values[$element['#delta']]);
1526
    $handler->entityFormLanguageWidgetSubmit($element, $element_form_state);
1527
  }
1528

    
1529
  // Now validate required elements if the entity is not empty.
1530
  if (!field_collection_item_is_empty($field_collection_item) && !empty($element['#field_collection_required_elements'])) {
1531
    foreach ($element['#field_collection_required_elements'] as &$elements) {
1532

    
1533
      // Copied from _form_validate().
1534
      if (isset($elements['#needs_validation'])) {
1535
        $is_countable = is_array($elements['#value']) || $elements['#value'] instanceof Countable;
1536
        $is_empty_multiple = $is_countable && (!count($elements['#value']));
1537
        $is_empty_string = (is_string($elements['#value']) && drupal_strlen(trim($elements['#value'])) == 0);
1538
        $is_empty_value = ($elements['#value'] === 0);
1539
        $is_empty_option = (isset($elements['#options']['_none']) && $elements['#value'] == '_none');
1540

    
1541
        // Validate fields with hook_field_is_empty. This will handle cases when
1542
        // file entity passes validation when it shouldn't.
1543
        $is_empty_field = FALSE;
1544
        if (isset($elements['#field_name'])) {
1545
          $field = field_info_field($elements['#field_name']);
1546
          // Extract field values array with all columns from form_state.
1547
          // The field we're looking at is always 3 levels deeper than field
1548
          // collection field.
1549
          $field_depth = count($elements['#field_parents']) + 3;
1550
          $field_values = drupal_array_get_nested_value($form_state['values'], array_slice($elements['#array_parents'], 0, $field_depth));
1551

    
1552
          // Special case lists since we don't get the correct array_parents.
1553
          if (count($elements['#array_parents']) < $field_depth && is_array($field_values)) {
1554
            $field_values = reset($field_values);
1555
          }
1556

    
1557
          $is_empty_field = module_invoke($field['module'], 'field_is_empty', $field_values, $field);
1558
        }
1559

    
1560
        if ($is_empty_multiple || $is_empty_string || $is_empty_value || $is_empty_option || $is_empty_field) {
1561
          if (isset($elements['#title'])) {
1562
            form_error($elements, t('@name field is required in the @collection collection.', array(
1563
              '@name' => $elements['#title'],
1564
              '@collection' => $field_state['instance']['label'],
1565
            )));
1566
          }
1567
          else {
1568
            form_error($elements);
1569
          }
1570
        }
1571
      }
1572
    }
1573
  }
1574

    
1575
  // Only if the form is being submitted, finish the collection entity and
1576
  // prepare it for saving.
1577
  if ($form_state['submitted'] && !form_get_errors()) {
1578

    
1579
    field_attach_submit('field_collection_item', $field_collection_item, $element, $form_state);
1580

    
1581
    // Load initial form values into $item, so any other form values below the
1582
    // same parents are kept.
1583
    $item = drupal_array_get_nested_value($form_state['values'], $element['#parents']);
1584

    
1585
    // Set the _weight if it is a multiple field.
1586
    if (isset($element['_weight']) && ($field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED)) {
1587
      $item['_weight'] = $element['_weight']['#value'];
1588
    }
1589

    
1590
    // Ensure field columns are poroperly populated.
1591
    $item['value'] = $field_collection_item->item_id;
1592
    $item['revision_id'] = $field_collection_item->revision_id;
1593

    
1594
    // Put the field collection item in $item['entity'], so it is saved with
1595
    // the host entity via hook_field_presave() / field API if it is not empty.
1596
    // @see field_collection_field_presave()
1597
    $item['entity'] = $field_collection_item;
1598
    form_set_value($element, $item, $form_state);
1599
  }
1600

    
1601
}
1602

    
1603
/**
1604
 * Implements hook_field_create_field().
1605
 */
1606
function field_collection_field_create_field($field) {
1607
  if ($field['type'] == 'field_collection') {
1608
    field_attach_create_bundle('field_collection_item', $field['field_name']);
1609

    
1610
    // Clear caches.
1611
    entity_info_cache_clear();
1612
    // Do not directly issue menu rebuilds here to avoid potentially multiple
1613
    // rebuilds. Instead, let menu_get_item() issue the rebuild on the next
1614
    // request.
1615
    variable_set('menu_rebuild_needed', TRUE);
1616
  }
1617
}
1618

    
1619
/**
1620
 * Implements hook_field_delete_field().
1621
 */
1622
function field_collection_field_delete_field($field) {
1623
  if ($field['type'] == 'field_collection') {
1624
    // Notify field.module that field collection was deleted.
1625
    field_attach_delete_bundle('field_collection_item', $field['field_name']);
1626

    
1627
    // Clear caches.
1628
    entity_info_cache_clear();
1629
    // Do not directly issue menu rebuilds here to avoid potentially multiple
1630
    // rebuilds. Instead, let menu_get_item() issue the rebuild on the next
1631
    // request.
1632
    variable_set('menu_rebuild_needed', TRUE);
1633
  }
1634
}
1635

    
1636
/**
1637
 * Implements hook_i18n_string_list_{textgroup}_alter().
1638
 */
1639
function field_collection_i18n_string_list_field_alter(&$properties, $type, $instance) {
1640
  if ($type == 'field_instance') {
1641
    $field = field_info_field($instance['field_name']);
1642

    
1643
    if ($field['type'] == 'field_collection' && !empty($instance['display'])) {
1644

    
1645
      foreach ($instance['display'] as $view_mode => $display) {
1646
        if ($display['type'] != 'field_collection_fields') {
1647
          $display['settings'] += array('edit' => 'edit', 'translate' => 'translate', 'delete' => 'delete', 'add' => 'add');
1648

    
1649
          $properties['field'][$instance['field_name']][$instance['bundle']]['setting_edit'] = array(
1650
            'title' => t('Edit link title'),
1651
            'string' => $display['settings']['edit'],
1652
          );
1653
          $properties['field'][$instance['field_name']][$instance['bundle']]['setting_translate'] = array(
1654
            'title' => t('Edit translate title'),
1655
            'string' => $display['settings']['translate'],
1656
          );
1657
          $properties['field'][$instance['field_name']][$instance['bundle']]['setting_delete'] = array(
1658
            'title' => t('Delete link title'),
1659
            'string' => $display['settings']['delete'],
1660
          );
1661
          $properties['field'][$instance['field_name']][$instance['bundle']]['setting_add'] = array(
1662
            'title' => t('Add link title'),
1663
            'string' => $display['settings']['add'],
1664
          );
1665
        }
1666
      }
1667
    }
1668
  }
1669
}
1670

    
1671
/**
1672
 * Implements hook_views_api().
1673
 */
1674
function field_collection_views_api() {
1675
  return array(
1676
    'api' => '3.0-alpha1',
1677
    'path' => drupal_get_path('module', 'field_collection') . '/views',
1678
  );
1679
}
1680

    
1681
/**
1682
 * Implements hook_features_pipe_COMPONENT_alter() for field objects.
1683
 *
1684
 * This is used with Features v1.0 and v2.0 prior to beta2, newer releases
1685
 * separated the field_base from the field_instance so this won't be used.
1686
 *
1687
 * @see field_collection_features_pipe_field_instance_alter().
1688
 */
1689
function field_collection_features_pipe_field_alter(&$pipe, $data, $export) {
1690
  // Skip this if Features has been updated to v2.0-beta2 or newer as it will
1691
  // use the separate field_instance integration instead.
1692
  if (!function_exists('field_instance_features_export_options')) {
1693
    // Add the fields of the field collection entity to the pipe.
1694
    foreach ($data as $identifier) {
1695
      if (($field = features_field_load($identifier)) && $field['field_config']['type'] == 'field_collection') {
1696
        $fields = field_info_instances('field_collection_item', $field['field_config']['field_name']);
1697
        foreach ($fields as $name => $field) {
1698
          $pipe['field'][] = "{$field['entity_type']}-{$field['bundle']}-{$field['field_name']}";
1699
        }
1700
      }
1701
    }
1702
  }
1703
}
1704

    
1705
/**
1706
 * Implements hook_features_pipe_COMPONENT_alter() for field_instance objects.
1707
 *
1708
 * This is used with Features v2.0-beta2 and newer.
1709
 */
1710
function field_collection_features_pipe_field_instance_alter(&$pipe, $data, $export) {
1711
  // Add the fields of the field collection entity to the pipe.
1712
  foreach ($data as $identifier) {
1713
    if (($field = features_field_load($identifier)) && $field['field_config']['type'] == 'field_collection') {
1714
      $fields = field_info_instances('field_collection_item', $field['field_config']['field_name']);
1715
      foreach ($fields as $name => $field) {
1716
        $pipe['field_instance'][] = "{$field['entity_type']}-{$field['bundle']}-{$field['field_name']}";
1717
      }
1718
    }
1719
  }
1720
}
1721

    
1722
/**
1723
 * Callback for generating entity metadata property info for our field instances.
1724
 *
1725
 * @see field_collection_field_info()
1726
 */
1727
function field_collection_entity_metadata_property_callback(&$info, $entity_type, $field, $instance, $field_type) {
1728
  $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$field['field_name']];
1729
  // Set the bundle as we know it is the name of the field.
1730
  $property['bundle'] = $field['field_name'];
1731
  $property['getter callback'] = 'field_collection_field_property_get';
1732
  $property['setter callback'] = 'field_collection_field_property_set';
1733
}
1734

    
1735
/**
1736
 * Entity property info setter callback for the host entity property.
1737
 *
1738
 * As the property is of type entity, the value will be passed as a wrapped
1739
 * entity.
1740
 */
1741
function field_collection_item_set_host_entity($item, $property_name, $wrapper) {
1742
  if (empty($item->is_new)) {
1743
    throw new EntityMetadataWrapperException('The host entity may be set only during creation of a field collection item.');
1744
  }
1745
  if (!isset($wrapper->{$item->field_name})) {
1746
    throw new EntityMetadataWrapperException('The specified entity has no such field collection field.');
1747
  }
1748
  $entity_type = $wrapper->type();
1749
  $field = field_info_field($item->field_name);
1750
  $langcode = field_is_translatable($entity_type, $field) ? field_collection_entity_language($entity_type, $wrapper->value()) : LANGUAGE_NONE;
1751
  $item->setHostEntity($wrapper->type(), $wrapper->value(), $langcode);
1752
}
1753

    
1754
/**
1755
 * Entity property info getter callback for the host entity property.
1756
 */
1757
function field_collection_item_get_host_entity($item) {
1758
  // As the property is defined as 'entity', we have to return a wrapped entity.
1759
  return entity_metadata_wrapper($item->hostEntityType(), $item->hostEntity());
1760
}
1761

    
1762
/**
1763
 * Entity property info getter callback for the field collection items.
1764
 *
1765
 * Like entity_metadata_field_property_get(), but additionally supports getting
1766
 * not-yet saved collection items from @code $item['entity'] @endcode.
1767
 */
1768
function field_collection_field_property_get($entity, array $options, $name, $entity_type, $info) {
1769
  $field = field_info_field($name);
1770
  $langcode = field_language($entity_type, $entity, $name, isset($options['language']) ? $options['language']->language : NULL);
1771
  $values = array();
1772
  if (isset($entity->{$name}[$langcode])) {
1773
    foreach ($entity->{$name}[$langcode] as $delta => $data) {
1774
      // Wrappers do not support multiple entity references being revisions or
1775
      // not yet saved entities. In the case of a single reference we can return
1776
      // the entity object though.
1777
      if ($field['cardinality'] == 1) {
1778
        $values[$delta] = field_collection_field_get_entity($data);
1779
      }
1780
      elseif (isset($data['value'])) {
1781
        $values[$delta] = $data['value'];
1782
      }
1783
    }
1784
  }
1785
  // For an empty single-valued field, we have to return NULL.
1786
  return $field['cardinality'] == 1 ? ($values ? reset($values) : NULL) : $values;
1787
}
1788

    
1789
/**
1790
 * Entity property info setter callback for the field collection items.
1791
 *
1792
 * Like entity_metadata_field_property_set(), but additionally supports
1793
 * saving the revision id.
1794
 */
1795
function field_collection_field_property_set($entity, $name, $value, $langcode, $entity_type) {
1796
  $field = field_info_field($name);
1797
  $columns = array_keys($field['columns']);
1798
  $langcode = entity_metadata_field_get_language($entity_type, $entity, $field, $langcode);
1799
  $values = $field['cardinality'] == 1 ? array($value) : (array) $value;
1800

    
1801
  $items = array();
1802
  foreach ($values as $delta => $value) {
1803
    if (isset($value)) {
1804
      if ($value instanceof FieldCollectionItemEntity) {
1805
        $items[$delta][$columns[0]] = $value->item_id;
1806
        $items[$delta][$columns[1]] = $value->revision_id;
1807
      }
1808
      elseif (is_array($value) && isset($value['value']) && isset($value['revision_id'])) {
1809
        $items[$delta][$columns[0]] = $value['value'];
1810
        $items[$delta][$columns[1]] = $value['revision_id'];
1811
      }
1812
      else {
1813
        $item = field_collection_item_load($value);
1814
        $items[$delta][$columns[0]] = $item->item_id;
1815
        $items[$delta][$columns[1]] = $item->revision_id;
1816
      }
1817
    }
1818
  }
1819
  $entity->{$name}[$langcode] = $items;
1820
  // Empty the static field language cache, so the field system picks up any
1821
  // possible new languages.
1822
  drupal_static_reset('field_language');
1823
}
1824

    
1825
/**
1826
 * Implements hook_devel_generate().
1827
 */
1828
function field_collection_devel_generate($object, $field, $instance, $bundle) {
1829
  // Create a new field collection object and add fake data to its fields.
1830
  $field_collection = entity_create('field_collection_item', array('field_name' => $field['field_name']));
1831
  $field_collection->language = $object->language;
1832
  $field_collection->setHostEntity($instance['entity_type'], $object, $object->language, FALSE);
1833

    
1834
  devel_generate_fields($field_collection, 'field_collection_item', $field['field_name']);
1835

    
1836
  $field_collection->save(TRUE);
1837

    
1838
  return array(
1839
    'value' => $field_collection->item_id,
1840
    'revision_id' => $field_collection->revision_id,
1841
  );
1842
}
1843

    
1844
/**
1845
 * Determine if field collection items can be translated.
1846
 *
1847
 * @return
1848
 *   Boolean indicating whether field collection items can be translated.
1849
 */
1850
function field_collection_item_is_translatable() {
1851
  return (bool) module_invoke('entity_translation', 'enabled', 'field_collection_item');
1852
}
1853

    
1854
/**
1855
 * Implements hook_entity_translation_delete().
1856
 */
1857
function field_collection_entity_translation_delete($entity_type, $entity, $langcode) {
1858
  if (field_collection_item_is_translatable()) {
1859
    list(, , $bundle) = entity_extract_ids($entity_type, $entity);
1860

    
1861
    foreach (field_info_instances($entity_type, $bundle) as $instance) {
1862
      $field_name = $instance['field_name'];
1863
      $field = field_info_field($field_name);
1864

    
1865
      if ($field['type'] == 'field_collection') {
1866
        $field_langcode = field_is_translatable($entity_type, $field) ? $langcode : LANGUAGE_NONE;
1867

    
1868
        if (!empty($entity->{$field_name}[$field_langcode])) {
1869
          foreach ($entity->{$field_name}[$field_langcode] as $delta => $item) {
1870
            $field_collection_item = field_collection_field_get_entity($item);
1871
            $handler = entity_translation_get_handler('field_collection_item', $field_collection_item);
1872
            $translations = $handler->getTranslations();
1873

    
1874
            if (isset($translations->data[$langcode])) {
1875
              $handler->removeTranslation($langcode);
1876
              $field_collection_item->save(TRUE);
1877
            }
1878
          }
1879
        }
1880
      }
1881
    }
1882
  }
1883
}
1884

    
1885
/**
1886
 * Determines if the additional blank items should be displayed or not.
1887
 *
1888
 * @param array $field
1889
 *   The field info array.
1890
 *
1891
 * @return bool
1892
 *   TRUE if the additional blank items should be hidden, and FALSE if not.
1893
 */
1894
function field_collection_hide_blank_items($field) {
1895
  return !empty($field['settings']['hide_blank_items']) && $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED;
1896
}
1897

    
1898
/**
1899
 * Implements hook_admin_menu_map().
1900
 */
1901
function field_collection_admin_menu_map() {
1902
  if (user_access('administer field collections')) {
1903
    $map['admin/structure/field-collections/%field_collection_field_name'] = array(
1904
      'parent' => 'admin/structure/field-collections',
1905
      'arguments' => array(
1906
        array('%field_collection_field_name' => array_keys(field_read_fields(array('type' => 'field_collection')))),
1907
      ),
1908
    );
1909
    return $map;
1910
  }
1911
}
1912

    
1913
/**
1914
 * implements hook_entity_translation_insert
1915
 */
1916
function field_collection_entity_translation_insert($entity_type, $entity, $translation, $values = array()) {
1917
  // Check if some of the values inserted are of a field_collection field
1918
  if (!empty($values)) {
1919
    foreach ($values as $field_name => $value) {
1920
      $field = field_info_field($field_name);
1921

    
1922
      if ($field['type'] == 'field_collection') {
1923
        // We have found a field collection
1924
        $language = $translation['language'];
1925
        $source_language = $translation['source'];
1926

    
1927
        if (!empty($value[$language])) {
1928
          $source_items = !empty($entity->{$field_name}[$source_language]) ? field_collection_field_item_to_ids($entity->{$field_name}[$source_language]) : array();
1929
          foreach ($value[$language] as $delta => $field_value) {
1930
            if (!isset($field_value['entity'])) {
1931
              if ($fc_entity = field_collection_field_get_entity($field_value)) {
1932
                // Check if this field collection item belongs to the source language
1933
                if (in_array($fc_entity->item_id, $source_items)) {
1934
                  // Clone the field collection item
1935
                  $new_fc_entity = clone $fc_entity;
1936
                  $new_fc_entity->item_id = NULL;
1937
                  $new_fc_entity->revision_id = NULL;
1938
                  $new_fc_entity->is_new = TRUE;
1939

    
1940
                  // Set the new entity for saving it later
1941
                  $entity->{$field_name}[$language][$delta]['entity'] = $new_fc_entity;
1942
                }
1943
              }
1944
            }
1945
          }
1946
        }
1947
      }
1948
    }
1949
  }
1950
}