Projet

Général

Profil

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

root / drupal7 / sites / all / modules / field_collection / field_collection.module @ b42754b9

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
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 field_collection_item
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
        'delete' => t('Delete'),
778
        'add' => t('Add'),
779
        'description' => TRUE,
780
        'view_mode' => 'full',
781
      ),
782
    ),
783
    'field_collection_fields' => array(
784
      'label' => t('Fields only'),
785
      'field types' => array('field_collection'),
786
      'settings' =>  array(
787
        'view_mode' => 'full',
788
      ),
789
    ),
790
  );
791
}
792

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

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

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

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

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

    
853
  return $elements;
854
}
855

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

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

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

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

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

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

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

    
913
    case 'field_collection_view':
914

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

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

    
946
    case 'field_collection_fields':
947

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

    
957
  return $element;
958
}
959

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

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

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

    
980
  return $operations;
981
}
982

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

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

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

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

    
1022
  return $element;
1023
}
1024

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1190
      $recursion--;
1191
      return $element;
1192
  }
1193
}
1194

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1314
  $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
1315

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

    
1321
  return $element;
1322
}
1323

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

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

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

    
1348
  $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
1349

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

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

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

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

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

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

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

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

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

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

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

    
1419
  $form_state['rebuild'] = TRUE;
1420
}
1421

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

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

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

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

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

    
1497
  $field_state = field_form_get_state($field_parents, $field_name, $language, $form_state);
1498

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

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

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

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

    
1531
      // Copied from _form_validate().
1532
      if (isset($elements['#needs_validation'])) {
1533
        $is_empty_multiple = (!count($elements['#value']));
1534
        $is_empty_string = (is_string($elements['#value']) && drupal_strlen(trim($elements['#value'])) == 0);
1535
        $is_empty_value = ($elements['#value'] === 0);
1536
        $is_empty_option = (isset($elements['#options']['_none']) && $elements['#value'] == '_none');
1537

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

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

    
1554
          $is_empty_field = module_invoke($field['module'], 'field_is_empty', $field_values, $field);
1555
        }
1556

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

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

    
1576
    field_attach_submit('field_collection_item', $field_collection_item, $element, $form_state);
1577

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

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

    
1587
    // Ensure field columns are poroperly populated.
1588
    $item['value'] = $field_collection_item->item_id;
1589
    $item['revision_id'] = $field_collection_item->revision_id;
1590

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

    
1598
}
1599

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1831
  devel_generate_fields($field_collection, 'field_collection_item', $field['field_name']);
1832

    
1833
  $field_collection->save(TRUE);
1834

    
1835
  return array(
1836
    'value' => $field_collection->item_id,
1837
    'revision_id' => $field_collection->revision_id,
1838
  );
1839
}
1840

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

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

    
1858
    foreach (field_info_instances($entity_type, $bundle) as $instance) {
1859
      $field_name = $instance['field_name'];
1860
      $field = field_info_field($field_name);
1861

    
1862
      if ($field['type'] == 'field_collection') {
1863
        $field_langcode = field_is_translatable($entity_type, $field) ? $langcode : LANGUAGE_NONE;
1864

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

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

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

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

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

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

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

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