field_collection.module

Tracking 7.x-1.x branch
  1. drupal
    1. 7 contributions/field_collection/field_collection.module

Module implementing field collection field type.

Classes

NameDescription
FieldCollectionItemEntityClass for field_collection_item entities.

Functions & methods

NameDescription
field_collection_admin_page_titleMenu title callback.
field_collection_admin_pathsImplements hook_admin_paths().
field_collection_devel_generateImplements hook_devel_generate().
field_collection_entity_infoImplements hook_entity_info().
field_collection_entity_metadata_property_callbackCallback for generating entity metadata property info for our field instances.
field_collection_features_pipe_field_alterImplements hook_features_pipe_component_alter() for fields.
field_collection_field_attach_formImplements hook_field_attach_form().
field_collection_field_create_fieldImplements hook_field_create_field().
field_collection_field_deleteImplements hook_field_delete().
field_collection_field_delete_fieldImplements hook_field_delete_field().
field_collection_field_delete_revisionImplements hook_field_delete_revision().
field_collection_field_formatter_infoImplements hook_field_formatter_info().
field_collection_field_formatter_linksHelper function to add links to a field collection field.
field_collection_field_formatter_settings_formImplements hook_field_formatter_settings_form().
field_collection_field_formatter_settings_summaryImplements hook_field_formatter_settings_summary().
field_collection_field_formatter_viewImplements hook_field_formatter_view().
field_collection_field_get_entityGets a field collection item entity for a given field item.
field_collection_field_get_pathReturns the base path to use for field collection items.
field_collection_field_infoImplements hook_field_info().
field_collection_field_instance_settings_formImplements hook_field_instance_settings_form().
field_collection_field_is_emptyImplements hook_field_is_empty().
field_collection_field_item_to_idsGet an array of field collection item IDs stored in the given field items.
field_collection_field_name_loadMenu callback for loading the bundle names.
field_collection_field_presaveImplements hook_field_presave().
field_collection_field_property_getEntity property info getter callback for the field collection items.
field_collection_field_settings_formImplements hook_field_settings_form().
field_collection_field_updateImplements hook_field_update().
field_collection_field_widget_embed_delay_required_validationFAPI #after_build of an individual field collection element to delay the validation of #required.
field_collection_field_widget_embed_validateFAPI validation of an individual field collection element.
field_collection_field_widget_formImplements hook_field_widget_form().
field_collection_field_widget_infoImplements hook_field_widget_info().
field_collection_field_widget_render_required#pre_render callback that ensures the element is rendered as being required.
field_collection_helpImplements hook_help().
field_collection_i18n_string_list_field_alterImplements hook_i18n_string_list_{textgroup}_alter().
field_collection_item_accessDetermines whether the given user has access to a field collection.
field_collection_item_get_host_entityEntity property info getter callback for the host entity property.
field_collection_item_is_emptyDetermines whether a field collection item entity is empty based on the collection-fields.
field_collection_item_loadLoads a field collection item.
field_collection_item_load_multipleLoads field collection items.
field_collection_item_revision_loadLoads a field collection revision.
field_collection_item_set_host_entityEntity property info setter callback for the host entity property.
field_collection_menuImplements hook_menu().
field_collection_menu_alterImplements hook_menu_alter() to fix the field collections admin UI tabs.
field_collection_permissionImplements hook_permission().
field_collection_remove_jsPage callback to handle AJAX for removing a field collection item.
field_collection_remove_submitSubmit callback to remove an item from the field UI multiple wrapper.
field_collection_themeImplements hook_theme().
field_collection_views_apiImplements hook_views_api().
theme_field_collection_viewThemes field collection items printed using the field_collection_view formatter.
_field_collection_collect_required_elements

File

View source
  1. <?php
  2. /**
  3. * @file
  4. * Module implementing field collection field type.
  5. */
  6. /**
  7. * Implements hook_help().
  8. */
  9. function field_collection_help($path, $arg) {
  10. switch ($path) {
  11. case 'admin/help#field_collection':
  12. $output = '';
  13. $output .= '<h3>' . t('About') . '</h3>';
  14. $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>';
  15. return $output;
  16. }
  17. }
  18. /**
  19. * Implements hook_entity_info().
  20. */
  21. function field_collection_entity_info() {
  22. $return['field_collection_item'] = array(
  23. 'label' => t('Field collection item'),
  24. 'label callback' => 'entity_class_label',
  25. 'uri callback' => 'entity_class_uri',
  26. 'entity class' => 'FieldCollectionItemEntity',
  27. 'controller class' => 'EntityAPIController',
  28. 'base table' => 'field_collection_item',
  29. 'revision table' => 'field_collection_item_revision',
  30. 'fieldable' => TRUE,
  31. 'entity keys' => array(
  32. 'id' => 'item_id',
  33. 'revision' => 'revision_id',
  34. 'bundle' => 'field_name',
  35. ),
  36. 'module' => 'field_collection',
  37. 'view modes' => array(
  38. 'full' => array(
  39. 'label' => t('Full content'),
  40. 'custom settings' => FALSE,
  41. ),
  42. ),
  43. 'access callback' => 'field_collection_item_access',
  44. 'metadata controller class' => 'FieldCollectionItemMetadataController'
  45. );
  46. // Add info about the bundles. We do not use field_info_fields() but directly
  47. // use field_read_fields() as field_info_fields() requires built entity info
  48. // to work.
  49. foreach (field_read_fields(array('type' => 'field_collection')) as $field_name => $field) {
  50. $return['field_collection_item']['bundles'][$field_name] = array(
  51. 'label' => t('Field collection @field', array('@field' => $field_name)),
  52. 'admin' => array(
  53. 'path' => 'admin/structure/field-collections/%field_collection_field_name',
  54. 'real path' => 'admin/structure/field-collections/' . strtr($field_name, array('_' => '-')),
  55. 'bundle argument' => 3,
  56. 'access arguments' => array('administer field collections'),
  57. ),
  58. );
  59. }
  60. return $return;
  61. }
  62. /**
  63. * Menu callback for loading the bundle names.
  64. */
  65. function field_collection_field_name_load($arg) {
  66. $field_name = strtr($arg, array('-' => '_'));
  67. if (($field = field_info_field($field_name)) && $field['type'] == 'field_collection') {
  68. return $field_name;
  69. }
  70. }
  71. /**
  72. * Loads a field collection item.
  73. *
  74. * @return field_collection_item
  75. * The field collection item entity or FALSE.
  76. */
  77. function field_collection_item_load($item_id, $reset = FALSE) {
  78. $result = field_collection_item_load_multiple(array($item_id), array(), $reset);
  79. return $result ? reset($result) : FALSE;
  80. }
  81. /**
  82. * Loads a field collection revision.
  83. *
  84. * @param $revision_id
  85. * The field collection revision ID.
  86. */
  87. function field_collection_item_revision_load($revision_id) {
  88. return entity_revision_load('field_collection_item', $revision_id);
  89. }
  90. /**
  91. * Loads field collection items.
  92. *
  93. * @return
  94. * An array of field collection item entities.
  95. */
  96. function field_collection_item_load_multiple($ids = array(), $conditions = array(), $reset = FALSE) {
  97. return entity_load('field_collection_item', $ids, $conditions, $reset);
  98. }
  99. /**
  100. * Class for field_collection_item entities.
  101. */
  102. class FieldCollectionItemEntity extends Entity {
  103. /**
  104. * Field collection field info.
  105. *
  106. * @var array
  107. */
  108. protected $fieldInfo;
  109. /**
  110. * The host entity object.
  111. *
  112. * @var object
  113. */
  114. protected $hostEntity;
  115. /**
  116. * The host entity ID.
  117. *
  118. * @var integer
  119. */
  120. protected $hostEntityId;
  121. /**
  122. * The host entity revision ID if this is not the default revision.
  123. *
  124. * @var integer
  125. */
  126. protected $hostEntityRevisionId;
  127. /**
  128. * The host entity type.
  129. *
  130. * @var string
  131. */
  132. protected $hostEntityType;
  133. /**
  134. * The language under which the field collection item is stored.
  135. *
  136. * @var string
  137. */
  138. protected $langcode = LANGUAGE_NONE;
  139. /**
  140. * Entity ID.
  141. *
  142. * @var integer
  143. */
  144. public $item_id;
  145. /**
  146. * Field collection revision ID.
  147. *
  148. * @var integer
  149. */
  150. public $revision_id;
  151. /**
  152. * The name of the field-collection field this item is associated with.
  153. *
  154. * @var string
  155. */
  156. public $field_name;
  157. /**
  158. * Whether this revision is the default revision.
  159. *
  160. * @var bool
  161. */
  162. public $default_revision = TRUE;
  163. /**
  164. * Whether the field collection item is archived, i.e. not in use.
  165. *
  166. * @see FieldCollectionItemEntity::isInUse()
  167. * @var bool
  168. */
  169. public $archived = FALSE;
  170. /**
  171. * Constructs the entity object.
  172. */
  173. public function __construct(array $values = array(), $entityType = NULL) {
  174. parent::__construct($values, 'field_collection_item');
  175. // Workaround issues http://drupal.org/node/1084268 and
  176. // http://drupal.org/node/1264440:
  177. // Check if the required property is set before checking for the field's
  178. // type. If the property is not set, we are hitting a PDO or a core's bug.
  179. // FIXME: Remove when #1264440 is fixed and the required PHP version is
  180. // properly identified and documented in the module documentation.
  181. if (isset($this->field_name)) {
  182. // Ok, we have the field name property, we can proceed and check the field's type
  183. $field_info = $this->fieldInfo();
  184. if (!$field_info || $field_info['type'] != 'field_collection') {
  185. throw new Exception("Invalid field name given: {$this->field_name} is not a Field Collection field.");
  186. }
  187. }
  188. }
  189. /**
  190. * Provides info about the field on the host entity, which embeds this
  191. * field collection item.
  192. */
  193. public function fieldInfo() {
  194. return field_info_field($this->field_name);
  195. }
  196. /**
  197. * Provides info of the field instance containing the reference to this
  198. * field collection item.
  199. */
  200. public function instanceInfo() {
  201. if ($this->fetchHostDetails()) {
  202. return field_info_instance($this->hostEntityType(), $this->field_name, $this->hostEntityBundle());
  203. }
  204. }
  205. /**
  206. * Returns the field instance label translated to interface language.
  207. */
  208. public function translatedInstanceLabel($langcode = NULL) {
  209. if ($info = $this->instanceInfo()) {
  210. if (module_exists('i18n_field')) {
  211. return i18n_string("field:{$this->field_name}:{$info['bundle']}:label", $info['label'], array('langcode' => $langcode));
  212. }
  213. return $info['label'];
  214. }
  215. }
  216. /**
  217. * Specifies the default label, which is picked up by label() by default.
  218. */
  219. public function defaultLabel() {
  220. // @todo make configurable.
  221. if ($this->fetchHostDetails()) {
  222. $field = $this->fieldInfo();
  223. $label = $this->translatedInstanceLabel();
  224. if ($field['cardinality'] == 1) {
  225. return $label;
  226. }
  227. elseif ($this->item_id) {
  228. return t('!instance_label @count', array('!instance_label' => $label, '@count' => $this->delta() + 1));
  229. }
  230. else {
  231. return t('New !instance_label', array('!instance_label' => $label));
  232. }
  233. }
  234. return t('Unconnected field collection item');
  235. }
  236. /**
  237. * Returns the path used to view the entity.
  238. */
  239. public function path() {
  240. if ($this->item_id) {
  241. return field_collection_field_get_path($this->fieldInfo()) . '/' . $this->item_id;
  242. }
  243. }
  244. /**
  245. * Returns the URI as returned by entity_uri().
  246. */
  247. public function defaultUri() {
  248. return array(
  249. 'path' => $this->path(),
  250. );
  251. }
  252. /**
  253. * Sets the host entity. Only possible during creation of a item.
  254. *
  255. * @param $create_link
  256. * (optional) Whether a field-item linking the host entity to the field
  257. * collection item should be created.
  258. */
  259. public function setHostEntity($entity_type, $entity, $langcode = LANGUAGE_NONE, $create_link = TRUE) {
  260. if (!empty($this->is_new)) {
  261. $this->hostEntityType = $entity_type;;
  262. $this->hostEntity = $entity;
  263. $this->langcode = $langcode;
  264. list($this->hostEntityId, $this->hostEntityRevisionId) = entity_extract_ids($this->hostEntityType, $this->hostEntity);
  265. // If the host entity is not saved yet, set the id to FALSE. So
  266. // fetchHostDetails() does not try to load the host entity details.
  267. if (!isset($this->hostEntityId)) {
  268. $this->hostEntityId = FALSE;
  269. }
  270. // We are create a new field collection for a non-default entity, thus
  271. // set archived to TRUE.
  272. if (!entity_revision_is_default($entity_type, $entity)) {
  273. $this->hostEntityId = FALSE;
  274. $this->archived = TRUE;
  275. }
  276. if ($create_link) {
  277. $entity->{$this->field_name}[$this->langcode][] = array('entity' => $this);
  278. }
  279. }
  280. else {
  281. throw new Exception('The host entity may be set only during creation of a field collection item.');
  282. }
  283. }
  284. /**
  285. * Returns the host entity, which embeds this field collection item.
  286. */
  287. public function hostEntity() {
  288. if ($this->fetchHostDetails()) {
  289. if (!isset($this->hostEntity) && $this->isInUse()) {
  290. $this->hostEntity = entity_load_single($this->hostEntityType, $this->hostEntityId);
  291. }
  292. elseif (!isset($this->hostEntity) && $this->hostEntityRevisionId) {
  293. $this->hostEntity = entity_revision_load($this->hostEntityType, $this->hostEntityRevisionId);
  294. }
  295. return $this->hostEntity;
  296. }
  297. }
  298. /**
  299. * Returns the entity type of the host entity, which embeds this
  300. * field collection item.
  301. */
  302. public function hostEntityType() {
  303. if ($this->fetchHostDetails()) {
  304. return $this->hostEntityType;
  305. }
  306. }
  307. /**
  308. * Returns the id of the host entity, which embeds this field collection item.
  309. */
  310. public function hostEntityId() {
  311. if ($this->fetchHostDetails()) {
  312. if (!$this->hostEntityId && $this->hostEntityRevisionId) {
  313. $this->hostEntityId = entity_id($this->hostEntityType, $this->hostEntity());
  314. }
  315. return $this->hostEntityId;
  316. }
  317. }
  318. /**
  319. * Returns the bundle of the host entity, which embeds this field collection
  320. * item.
  321. */
  322. public function hostEntityBundle() {
  323. if ($entity = $this->hostEntity()) {
  324. list($id, $rev_id, $bundle) = entity_extract_ids($this->hostEntityType, $entity);
  325. return $bundle;
  326. }
  327. }
  328. protected function fetchHostDetails() {
  329. if (!isset($this->hostEntityId)) {
  330. if ($this->item_id) {
  331. // For saved field collections, query the field data to determine the
  332. // right host entity.
  333. $query = new EntityFieldQuery();
  334. $query->fieldCondition($this->fieldInfo(), 'revision_id', $this->revision_id);
  335. if (!$this->isInUse()) {
  336. $query->age(FIELD_LOAD_REVISION);
  337. }
  338. $result = $query->execute();
  339. list($this->hostEntityType, $data) = each($result);
  340. if ($this->isInUse()) {
  341. $this->hostEntityId = $data ? key($data) : FALSE;
  342. $this->hostEntityRevisionId = FALSE;
  343. }
  344. // If we are querying for revisions, we get the revision ID.
  345. else {
  346. $this->hostEntityId = FALSE;
  347. $this->hostEntityRevisionId = $data ? key($data) : FALSE;
  348. }
  349. }
  350. else {
  351. // No host entity available yet.
  352. $this->hostEntityId = FALSE;
  353. }
  354. }
  355. return !empty($this->hostEntityId) || !empty($this->hostEntity) || !empty($this->hostEntityRevisionId);
  356. }
  357. /**
  358. * Determines the $delta of the reference pointing to this field collection
  359. * item.
  360. */
  361. public function delta() {
  362. if (($entity = $this->hostEntity()) && isset($entity->{$this->field_name})) {
  363. foreach ($entity->{$this->field_name} as $langcode => &$data) {
  364. foreach ($data as $delta => $item) {
  365. if (isset($item['value']) && $item['value'] == $this->item_id) {
  366. $this->langcode = $langcode;
  367. return $delta;
  368. }
  369. elseif (isset($item['entity']) && $item['entity'] === $this) {
  370. $this->langcode = $langcode;
  371. return $delta;
  372. }
  373. }
  374. }
  375. }
  376. }
  377. /**
  378. * Determines the language code under which the item is stored.
  379. */
  380. public function langcode() {
  381. if ($this->delta() != NULL) {
  382. return $this->langcode;
  383. }
  384. }
  385. /**
  386. * Determines whether this field collection item revision is in use.
  387. *
  388. * Field collection items may be contained in from non-default host entity
  389. * revisions. If the field collection item does not appear in the default
  390. * host entity revision, the item is actually not used by default and so
  391. * marked as 'archived'.
  392. * If the field collection item appears in the default revision of the host
  393. * entity, the default revision of the field collection item is in use there
  394. * and the collection is not marked as archived.
  395. */
  396. public function isInUse() {
  397. return $this->default_revision && !$this->archived;
  398. }
  399. /**
  400. * Save the field collection item.
  401. *
  402. * By default, always save the host entity, so modules are able to react
  403. * upon changes to the content of the host and any 'last updated' dates of
  404. * entities get updated.
  405. *
  406. * For creating an item a host entity has to be specified via setHostEntity()
  407. * before this function is invoked. For the link between the entities to be
  408. * fully established, the host entity object has to be updated to include a
  409. * reference on this field collection item during saving. So do not skip
  410. * saving the host for creating items.
  411. *
  412. * @param $skip_host_save
  413. * (internal) If TRUE is passed, the host entity is not saved automatically
  414. * and therefore no link is created between the host and the item or
  415. * revision updates might be skipped. Use with care.
  416. */
  417. public function save($skip_host_save = FALSE) {
  418. // Make sure we have a host entity during creation.
  419. if (!empty($this->is_new) && !(isset($this->hostEntityId) || isset($this->hostEntity) || isset($this->hostEntityRevisionId))) {
  420. throw new Exception("Unable to create a field collection item without a given host entity.");
  421. }
  422. // Only save directly if we are told to skip saving the host entity. Else,
  423. // we always save via the host as saving the host might trigger saving
  424. // field collection items anyway (e.g. if a new revision is created).
  425. if ($skip_host_save) {
  426. return entity_get_controller($this->entityType)->save($this);
  427. }
  428. else {
  429. $host_entity = $this->hostEntity();
  430. if (!$host_entity) {
  431. throw new Exception("Unable to save a field collection item without a valid reference to a host entity.");
  432. }
  433. // If this is creating a new revision, also do so for the host entity.
  434. if (!empty($this->revision) || !empty($this->is_new_revision)) {
  435. $host_entity->revision = TRUE;
  436. if (!empty($this->default_revision)) {
  437. entity_revision_set_default($this->hostEntityType, $host_entity);
  438. }
  439. }
  440. // Set the host entity reference, so the item will be saved with the host.
  441. // @see field_collection_field_presave()
  442. $delta = $this->delta();
  443. if (isset($delta)) {
  444. $host_entity->{$this->field_name}[$this->langcode][$delta] = array('entity' => $this);
  445. }
  446. else {
  447. $host_entity->{$this->field_name}[$this->langcode][] = array('entity' => $this);
  448. }
  449. return entity_save($this->hostEntityType, $host_entity);
  450. }
  451. }
  452. /**
  453. * Deletes the field collection item and the reference in the host entity.
  454. */
  455. public function delete() {
  456. parent::delete();
  457. $this->deleteHostEntityReference();
  458. }
  459. /**
  460. * Deletes the host entity's reference of the field collection item.
  461. */
  462. protected function deleteHostEntityReference() {
  463. $delta = $this->delta();
  464. if ($this->item_id && isset($delta)) {
  465. unset($this->hostEntity->{$this->field_name}[$this->langcode][$delta]);
  466. entity_save($this->hostEntityType, $this->hostEntity);
  467. }
  468. }
  469. /**
  470. * Intelligently delete a field collection item revision.
  471. *
  472. * If a host entity is revisioned with its field collection items, deleting
  473. * a field collection item on the default revision of the host should not
  474. * delete the collection item from archived revisions too. Instead, we delete
  475. * the current default revision and archive the field collection.
  476. *
  477. * If no revisions are left or the host is not revisionable, the whole item
  478. * is deleted.
  479. */
  480. public function deleteRevision($skip_host_update = FALSE) {
  481. if (!$this->revision_id) {
  482. return;
  483. }
  484. $info = entity_get_info($this->hostEntityType());
  485. if (empty($info['entity keys']['revision']) || !$this->hostEntity()) {
  486. return $this->delete();
  487. }
  488. if (!$skip_host_update) {
  489. // Just remove the item from the host, which cares about deleting the
  490. // item (depending on whether the update creates a new revision).
  491. $this->deleteHostEntityReference();
  492. }
  493. elseif (!$this->isDefaultRevision()) {
  494. entity_revision_delete('field_collection_item', $this->revision_id);
  495. }
  496. // If deleting the default revision, take care!
  497. else {
  498. $row = db_select('field_collection_item_revision', 'r')
  499. ->fields('r')
  500. ->condition('item_id', $this->item_id)
  501. ->condition('revision_id', $this->revision_id, '<>')
  502. ->execute()
  503. ->fetchAssoc();
  504. // If no other revision is left, delete. Else archive the item.
  505. if (!$row) {
  506. $this->delete();
  507. }
  508. else {
  509. // Make the other revision the default revision and archive the item.
  510. db_update('field_collection_item')
  511. ->fields(array('archived' => 1, 'revision_id' => $row['revision_id']))
  512. ->condition('item_id', $this->item_id)
  513. ->execute();
  514. entity_get_controller('field_collection_item')->resetCache(array($this->item_id));
  515. entity_revision_delete('field_collection_item', $this->revision_id);
  516. }
  517. }
  518. }
  519. /**
  520. * Export the field collection item.
  521. *
  522. * Since field collection entities are not directly exportable (i.e., do not
  523. * have 'exportable' set to TRUE in hook_entity_info()) and since Features
  524. * calls this method when exporting the field collection as a field attached
  525. * to another entity, we return the export in the format expected by
  526. * Features, rather than in the normal Entity::export() format.
  527. */
  528. public function export($prefix = '') {
  529. // Based on code in EntityDefaultFeaturesController::export_render().
  530. $export = "entity_import('" . $this->entityType() . "', '";
  531. $export .= addcslashes(parent::export(), '\\\'');
  532. $export .= "')";
  533. return $export;
  534. }
  535. /**
  536. * Magic method to only serialize what's necessary.
  537. */
  538. public function __sleep() {
  539. $vars = get_object_vars($this);
  540. unset($vars['entityInfo'], $vars['idKey'], $vars['nameKey'], $vars['statusKey']);
  541. unset($vars['fieldInfo']);
  542. // Also do not serialize the host entity, but only if it has already an id.
  543. if ($this->hostEntity && ($this->hostEntityId || $this->hostEntityRevisionId)) {
  544. unset($vars['hostEntity']);
  545. }
  546. // Also key the returned array with the variable names so the method may
  547. // be easily overridden and customized.
  548. return drupal_map_assoc(array_keys($vars));
  549. }
  550. /**
  551. * Magic method to invoke setUp() on unserialization.
  552. *
  553. * @todo: Remove this once it appears in a released entity API module version.
  554. */
  555. public function __wakeup() {
  556. $this->setUp();
  557. }
  558. }
  559. /**
  560. * Implements hook_menu().
  561. */
  562. function field_collection_menu() {
  563. $items = array();
  564. if (module_exists('field_ui')) {
  565. $items['admin/structure/field-collections'] = array(
  566. 'title' => 'Field collections',
  567. 'description' => 'Manage fields on field collections.',
  568. 'page callback' => 'field_collections_overview',
  569. 'access arguments' => array('administer field collections'),
  570. 'type' => MENU_NORMAL_ITEM,
  571. 'file' => 'field_collection.admin.inc',
  572. );
  573. }
  574. // Add menu paths for viewing/editing/deleting field collection items.
  575. foreach (field_info_fields() as $field) {
  576. if ($field['type'] == 'field_collection') {
  577. $path = field_collection_field_get_path($field);
  578. $count = count(explode('/', $path));
  579. $items[$path . '/%field_collection_item'] = array(
  580. 'page callback' => 'field_collection_item_page_view',
  581. 'page arguments' => array($count),
  582. 'access callback' => 'field_collection_item_access',
  583. 'access arguments' => array('view', $count),
  584. 'file' => 'field_collection.pages.inc',
  585. );
  586. $items[$path . '/%field_collection_item/view'] = array(
  587. 'title' => 'View',
  588. 'type' => MENU_DEFAULT_LOCAL_TASK,
  589. 'weight' => -10,
  590. );
  591. $items[$path . '/%field_collection_item/edit'] = array(
  592. 'page callback' => 'drupal_get_form',
  593. 'page arguments' => array('field_collection_item_form', $count),
  594. 'access callback' => 'field_collection_item_access',
  595. 'access arguments' => array('update', $count),
  596. 'title' => 'Edit',
  597. 'type' => MENU_LOCAL_TASK,
  598. 'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  599. 'file' => 'field_collection.pages.inc',
  600. );
  601. $items[$path . '/%field_collection_item/delete'] = array(
  602. 'page callback' => 'drupal_get_form',
  603. 'page arguments' => array('field_collection_item_delete_confirm', $count),
  604. 'access callback' => 'field_collection_item_access',
  605. 'access arguments' => array('delete', $count),
  606. 'title' => 'Delete',
  607. 'type' => MENU_LOCAL_TASK,
  608. 'context' => MENU_CONTEXT_INLINE,
  609. 'file' => 'field_collection.pages.inc',
  610. );
  611. // Add entity type and the entity id as additional arguments.
  612. $items[$path . '/add/%/%'] = array(
  613. 'page callback' => 'field_collection_item_add',
  614. 'page arguments' => array($field['field_name'], $count + 1, $count + 2),
  615. // The pace callback takes care of checking access itself.
  616. 'access callback' => TRUE,
  617. 'file' => 'field_collection.pages.inc',
  618. );
  619. // Add menu items for dealing with revisions.
  620. $items[$path . '/%field_collection_item/revisions/%field_collection_item_revision'] = array(
  621. 'page callback' => 'field_collection_item_page_view',
  622. 'page arguments' => array($count + 2),
  623. 'access callback' => 'field_collection_item_access',
  624. 'access arguments' => array('view', $count + 2),
  625. 'file' => 'field_collection.pages.inc',
  626. );
  627. }
  628. }
  629. $items['field_collection/ajax'] = array(
  630. 'title' => 'Remove item callback',
  631. 'page callback' => 'field_collection_remove_js',
  632. 'delivery callback' => 'ajax_deliver',
  633. 'access callback' => TRUE,
  634. 'theme callback' => 'ajax_base_page_theme',
  635. 'type' => MENU_CALLBACK,
  636. 'file path' => 'includes',
  637. 'file' => 'form.inc',
  638. );
  639. return $items;
  640. }
  641. /**
  642. * Implements hook_menu_alter() to fix the field collections admin UI tabs.
  643. */
  644. function field_collection_menu_alter(&$items) {
  645. if (module_exists('field_ui') && isset($items['admin/structure/field-collections/%field_collection_field_name/fields'])) {
  646. // Make the fields task the default local task.
  647. $items['admin/structure/field-collections/%field_collection_field_name'] = $items['admin/structure/field-collections/%field_collection_field_name/fields'];
  648. $item = &$items['admin/structure/field-collections/%field_collection_field_name'];
  649. $item['type'] = MENU_NORMAL_ITEM;
  650. $item['title'] = 'Manage fields';
  651. $item['title callback'] = 'field_collection_admin_page_title';
  652. $item['title arguments'] = array(3);
  653. $items['admin/structure/field-collections/%field_collection_field_name/fields'] = array(
  654. 'title' => 'Manage fields',
  655. 'type' => MENU_DEFAULT_LOCAL_TASK,
  656. 'weight' => 1,
  657. );
  658. }
  659. }
  660. /**
  661. * Menu title callback.
  662. */
  663. function field_collection_admin_page_title($field_name) {
  664. return t('Field collection @field_name', array('@field_name' => $field_name));
  665. }
  666. /**
  667. * Implements hook_admin_paths().
  668. */
  669. function field_collection_admin_paths() {
  670. if (variable_get('node_admin_theme')) {
  671. return array(
  672. 'field-collection/*/*/edit' => TRUE,
  673. 'field-collection/*/*/delete' => TRUE,
  674. 'field-collection/*/add/*/*' => TRUE,
  675. );
  676. }
  677. }
  678. /**
  679. * Implements hook_permission().
  680. */
  681. function field_collection_permission() {
  682. return array(
  683. 'administer field collections' => array(
  684. 'title' => t('Administer field collections'),
  685. 'description' => t('Create and delete fields on field collections.'),
  686. ),
  687. );
  688. }
  689. /**
  690. * Determines whether the given user has access to a field collection.
  691. *
  692. * @param $op
  693. * The operation being performed. One of 'view', 'update', 'create', 'delete'.
  694. * @param $item
  695. * Optionally a field collection item. If nothing is given, access for all
  696. * items is determined.
  697. * @param $account
  698. * The user to check for. Leave it to NULL to check for the global user.
  699. * @return boolean
  700. * Whether access is allowed or not.
  701. */
  702. function field_collection_item_access($op, FieldCollectionItemEntity $item = NULL, $account = NULL) {
  703. // We do not support editing field collection revisions that are not used at
  704. // the hosts default revision as saving the host might result in a new default
  705. // revision.
  706. if (isset($item) && !$item->isInUse() && $op != 'view') {
  707. return FALSE;
  708. }
  709. if (user_access('administer field collections', $account)) {
  710. return TRUE;
  711. }
  712. if (!isset($item)) {
  713. return FALSE;
  714. }
  715. $op = $op == 'view' ? 'view' : 'edit';
  716. // Access is determined by the entity and field containing the reference.
  717. $field = field_info_field($item->field_name);
  718. $entity_access = entity_access($op == 'view' ? 'view' : 'update', $item->hostEntityType(), $item->hostEntity(), $account);
  719. return $entity_access && field_access($op, $field, $item->hostEntityType(), $item->hostEntity(), $account);
  720. }
  721. /**
  722. * Implements hook_theme().
  723. */
  724. function field_collection_theme() {
  725. return array(
  726. 'field_collection_item' => array(
  727. 'render element' => 'elements',
  728. 'template' => 'field-collection-item',
  729. ),
  730. 'field_collection_view' => array(
  731. 'render element' => 'element',
  732. ),
  733. );
  734. }
  735. /**
  736. * Implements hook_field_info().
  737. */
  738. function field_collection_field_info() {
  739. return array(
  740. 'field_collection' => array(
  741. 'label' => t('Field collection'),
  742. 'description' => t('This field stores references to embedded entities, which itself may contain any number of fields.'),
  743. 'instance_settings' => array(),
  744. 'default_widget' => 'field_collection_hidden',
  745. 'default_formatter' => 'field_collection_view',
  746. // As of now there is no UI for setting the path.
  747. 'settings' => array(
  748. 'path' => '',
  749. 'hide_blank_items' => TRUE,
  750. ),
  751. // Add entity property info.
  752. 'property_type' => 'field_collection_item',
  753. 'property_callbacks' => array('field_collection_entity_metadata_property_callback'),
  754. ),
  755. );
  756. }
  757. /**
  758. * Implements hook_field_instance_settings_form().
  759. */
  760. function field_collection_field_instance_settings_form($field, $instance) {
  761. $element['fieldset'] = array(
  762. '#type' => 'fieldset',
  763. '#title' => t('Default value'),
  764. '#collapsible' => FALSE,
  765. // As field_ui_default_value_widget() does, we change the #parents so that
  766. // the value below is writing to $instance in the right location.
  767. '#parents' => array('instance'),
  768. );
  769. // Be sure to set the default value to NULL, e.g. to repair old fields
  770. // that still have one.
  771. $element['fieldset']['default_value'] = array(
  772. '#type' => 'value',
  773. '#value' => NULL,
  774. );
  775. $element['fieldset']['content'] = array(
  776. '#pre' => '<p>',
  777. '#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'))),
  778. '#suffix' => '</p>',
  779. );
  780. return $element;
  781. }
  782. /**
  783. * Returns the base path to use for field collection items.
  784. */
  785. function field_collection_field_get_path($field) {
  786. if (empty($field['settings']['path'])) {
  787. return 'field-collection/' . strtr($field['field_name'], array('_' => '-'));
  788. }
  789. return $field['settings']['path'];
  790. }
  791. /**
  792. * Implements hook_field_settings_form().
  793. */
  794. function field_collection_field_settings_form($field, $instance) {
  795. $form['hide_blank_items'] = array(
  796. '#type' => 'checkbox',
  797. '#title' => t('Hide blank items'),
  798. '#default_value' => $field['settings']['hide_blank_items'],
  799. '#description' => t("A blank item is always added to any multivalued field's form. If checked, any additional blank items are hidden except of the first item which is always shown."),
  800. '#weight' => 10,
  801. '#states' => array(
  802. // Hide the setting if the cardinality is 1.
  803. 'invisible' => array(
  804. ':input[name="field[cardinality]"]' => array('value' => '1'),
  805. ),
  806. ),
  807. );
  808. return $form;
  809. }
  810. /**
  811. * Implements hook_field_presave().
  812. *
  813. * Support saving field collection items in @code $item['entity'] @endcode. This
  814. * may be used to seamlessly create field collection items during host-entity
  815. * creation or to save changes to the host entity and its collections at once.
  816. */
  817. function field_collection_field_presave($host_entity_type, $host_entity, $field, $instance, $langcode, &$items) {
  818. foreach ($items as &$item) {
  819. // In case the entity has been changed / created, save it and set the id.
  820. // If the host entity creates a new revision, save new item-revisions as
  821. // well.
  822. if (isset($item['entity']) || !empty($host_entity->revision)) {
  823. if ($entity = field_collection_field_get_entity($item)) {
  824. if (!empty($entity->is_new)) {
  825. $entity->setHostEntity($host_entity_type, $host_entity, LANGUAGE_NONE, FALSE);
  826. }
  827. // If the host entity is saved as new revision, do the same for the item.
  828. if (!empty($host_entity->revision)) {
  829. $entity->revision = TRUE;
  830. $is_default = entity_revision_is_default($host_entity_type, $host_entity);
  831. // If an entity type does not support saving non-default entities,
  832. // assume it will be saved as default.
  833. if (!isset($is_default) || $is_default) {
  834. $entity->default_revision = TRUE;
  835. $entity->archived = FALSE;
  836. }
  837. }
  838. $entity->save(TRUE);
  839. $item = array(
  840. 'value' => $entity->item_id,
  841. 'revision_id' => $entity->revision_id,
  842. );
  843. }
  844. }
  845. }
  846. }
  847. /**
  848. * Implements hook_field_update().
  849. *
  850. * Care about removed field collection items.
  851. */
  852. function field_collection_field_update($entity_type, $entity, $field, $instance, $langcode, &$items) {
  853. $items_original = !empty($entity->original->{$field['field_name']}[$langcode]) ? $entity->original->{$field['field_name']}[$langcode] : array();
  854. $original_by_id = array_flip(field_collection_field_item_to_ids($items_original));
  855. foreach ($items as $item) {
  856. unset($original_by_id[$item['value']]);
  857. }
  858. // If there are removed items, care about deleting the item entities.
  859. if ($original_by_id) {
  860. $ids = array_flip($original_by_id);
  861. // If we are creating a new revision, the old-items should be kept but get
  862. // marked as archived now.
  863. if (!empty($entity->revision)) {
  864. db_update('field_collection_item')
  865. ->fields(array('archived' => 1))
  866. ->condition('item_id', $ids, 'IN')
  867. ->execute();
  868. }
  869. else {
  870. // Delete unused field collection items now.
  871. foreach (field_collection_item_load_multiple($ids) as $item) {
  872. $item->deleteRevision(TRUE);
  873. }
  874. }
  875. }
  876. }
  877. /**
  878. * Implements hook_field_delete().
  879. */
  880. function field_collection_field_delete($entity_type, $entity, $field, $instance, $langcode, &$items) {
  881. // Also delete all embedded entities.
  882. if ($ids = field_collection_field_item_to_ids($items)) {
  883. // We filter out entities that are still being referenced by other
  884. // host-entities. This should never be the case, but it might happened e.g.
  885. // when modules cloned a node without knowing about field-collection.
  886. $entity_info = entity_get_info($entity_type);
  887. $entity_id_name = $entity_info['entity keys']['id'];
  888. $field_column = key($field['columns']);
  889. foreach ($ids as $id_key => $id) {
  890. $query = new EntityFieldQuery();
  891. $entities = $query
  892. ->fieldCondition($field['field_name'], $field_column, $id)
  893. ->execute();
  894. unset($entities[$entity_type][$entity->$entity_id_name]);
  895. if (!empty($entities[$entity_type])) {
  896. // Filter this $id out.
  897. unset($ids[$id_key]);
  898. }
  899. }
  900. entity_delete_multiple('field_collection_item', $ids);
  901. }
  902. }
  903. /**
  904. * Implements hook_field_delete_revision().
  905. */
  906. function field_collection_field_delete_revision($entity_type, $entity, $field, $instance, $langcode, &$items) {
  907. foreach ($items as $item) {
  908. if (!empty($item['revision_id'])) {
  909. if ($entity = field_collection_item_revision_load($item['revision_id'])) {
  910. $entity->deleteRevision(TRUE);
  911. }
  912. }
  913. }
  914. }
  915. /**
  916. * Get an array of field collection item IDs stored in the given field items.
  917. */
  918. function field_collection_field_item_to_ids($items) {
  919. $ids = array();
  920. foreach ($items as $item) {
  921. if (!empty($item['value'])) {
  922. $ids[] = $item['value'];
  923. }
  924. }
  925. return $ids;
  926. }
  927. /**
  928. * Implements hook_field_is_empty().
  929. */
  930. function field_collection_field_is_empty($item, $field) {
  931. if (!empty($item['value'])) {
  932. return FALSE;
  933. }
  934. elseif (isset($item['entity'])) {
  935. return field_collection_item_is_empty($item['entity']);
  936. }
  937. return TRUE;
  938. }
  939. /**
  940. * Determines whether a field collection item entity is empty based on the collection-fields.
  941. */
  942. function field_collection_item_is_empty(FieldCollectionItemEntity $item) {
  943. $instances = field_info_instances('field_collection_item', $item->field_name);
  944. $is_empty = TRUE;
  945. foreach ($instances as $instance) {
  946. $field_name = $instance['field_name'];
  947. $field = field_info_field($field_name);
  948. // Determine the list of languages to iterate on.
  949. $languages = field_available_languages('field_collection_item', $field);
  950. foreach ($languages as $langcode) {
  951. if (!empty($item->{$field_name}[$langcode])) {
  952. // If at least one collection-field is not empty; the
  953. // field collection item is not empty.
  954. foreach ($item->{$field_name}[$langcode] as $field_item) {
  955. if (!module_invoke($field['module'], 'field_is_empty', $field_item, $field)) {
  956. $is_empty = FALSE;
  957. }
  958. }
  959. }
  960. }
  961. }
  962. // Allow other modules a chance to alter the value before returning.
  963. drupal_alter('field_collection_is_empty', $is_empty, $item);
  964. return $is_empty;
  965. }
  966. /**
  967. * Implements hook_field_formatter_info().
  968. */
  969. function field_collection_field_formatter_info() {
  970. return array(
  971. 'field_collection_list' => array(
  972. 'label' => t('Links to field collection items'),
  973. 'field types' => array('field_collection'),
  974. 'settings' => array(
  975. 'edit' => t('Edit'),
  976. 'delete' => t('Delete'),
  977. 'add' => t('Add'),
  978. 'description' => TRUE,
  979. ),
  980. ),
  981. 'field_collection_view' => array(
  982. 'label' => t('Field collection items'),
  983. 'field types' => array('field_collection'),
  984. 'settings' => array(
  985. 'edit' => t('Edit'),
  986. 'delete' => t('Delete'),
  987. 'add' => t('Add'),
  988. 'description' => TRUE,
  989. 'view_mode' => 'full',
  990. ),
  991. ),
  992. 'field_collection_fields' => array(
  993. 'label' => t('Fields only'),
  994. 'field types' => array('field_collection'),
  995. 'settings' => array(
  996. 'view_mode' => 'full',
  997. ),
  998. ),
  999. );
  1000. }
  1001. /**
  1002. * Implements hook_field_formatter_settings_form().
  1003. */
  1004. function field_collection_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  1005. $display = $instance['display'][$view_mode];
  1006. $settings = $display['settings'];
  1007. $elements = array();
  1008. if ($display['type'] != 'field_collection_fields') {
  1009. $elements['edit'] = array(
  1010. '#type' => 'textfield',
  1011. '#title' => t('Edit link title'),
  1012. '#default_value' => $settings['edit'],
  1013. '#description' => t('Leave the title empty, to hide the link.'),
  1014. );
  1015. $elements['delete'] = array(
  1016. '#type' => 'textfield',
  1017. '#title' => t('Delete link title'),
  1018. '#default_value' => $settings['delete'],
  1019. '#description' => t('Leave the title empty, to hide the link.'),
  1020. );
  1021. $elements['add'] = array(
  1022. '#type' => 'textfield',
  1023. '#title' => t('Add link title'),
  1024. '#default_value' => $settings['add'],
  1025. '#description' => t('Leave the title empty, to hide the link.'),
  1026. );
  1027. $elements['description'] = array(
  1028. '#type' => 'checkbox',
  1029. '#title' => t('Show the field description beside the add link.'),
  1030. '#default_value' => $settings['description'],
  1031. '#description' => t('If enabled and the add link is shown, the field description is shown in front of the add link.'),
  1032. );
  1033. }
  1034. // Add a select form element for view_mode if viewing the rendered field_collection.
  1035. if ($display['type'] !== 'field_collection_list') {
  1036. $entity_type = entity_get_info('field_collection_item');
  1037. $options = array();
  1038. foreach ($entity_type['view modes'] as $mode => $info) {
  1039. $options[$mode] = $info['label'];
  1040. }
  1041. $elements['view_mode'] = array(
  1042. '#type' => 'select',
  1043. '#title' => t('View mode'),
  1044. '#options' => $options,
  1045. '#default_value' => $settings['view_mode'],
  1046. '#description' => t('Select the view mode'),
  1047. );
  1048. }
  1049. return $elements;
  1050. }
  1051. /**
  1052. * Implements hook_field_formatter_settings_summary().
  1053. */
  1054. function field_collection_field_formatter_settings_summary($field, $instance, $view_mode) {
  1055. $display = $instance['display'][$view_mode];
  1056. $settings = $display['settings'];
  1057. $output = array();
  1058. if ($display['type'] !== 'field_collection_fields') {
  1059. $links = array_filter(array_intersect_key($settings, array_flip(array('add', 'edit', 'delete'))));
  1060. if ($links) {
  1061. $output[] = t('Links: @links', array('@links' => check_plain(implode(', ', $links))));
  1062. }
  1063. else {
  1064. $output[] = t('Links: none');
  1065. }
  1066. }
  1067. if ($display['type'] !== 'field_collection_list') {
  1068. $entity_type = entity_get_info('field_collection_item');
  1069. if (!empty($entity_type['view modes'][$settings['view_mode']]['label'])) {
  1070. $output[] = t('View mode: @mode', array('@mode' => $entity_type['view modes'][$settings['view_mode']]['label']));
  1071. }
  1072. }
  1073. return implode('<br>', $output);
  1074. }
  1075. /**
  1076. * Implements hook_field_formatter_view().
  1077. */
  1078. function field_collection_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  1079. $element = array();
  1080. $settings = $display['settings'];
  1081. switch ($display['type']) {
  1082. case 'field_collection_list':
  1083. foreach ($items as $delta => $item) {
  1084. if ($field_collection = field_collection_field_get_entity($item)) {
  1085. $output = l($field_collection->label(), $field_collection->path());
  1086. $links = array();
  1087. foreach (array('edit', 'delete') as $op) {
  1088. if ($settings[$op] && field_collection_item_access($op == 'edit' ? 'update' : $op, $field_collection)) {
  1089. $title = entity_i18n_string("field:{$field['field_name']}:{$instance['bundle']}:setting_$op", $settings[$op]);
  1090. $links[] = l($title, $field_collection->path() . '/' . $op, array('query' => drupal_get_destination()));
  1091. }
  1092. }
  1093. if ($links) {
  1094. $output .= ' (' . implode('|', $links) . ')';
  1095. }
  1096. $element[$delta] = array('#markup' => $output);
  1097. }
  1098. }
  1099. field_collection_field_formatter_links($element, $entity_type, $entity, $field, $instance, $langcode, $items, $display);
  1100. break;
  1101. case 'field_collection_view':
  1102. $element['#attached']['css'][] = drupal_get_path('module', 'field_collection') . '/field_collection.theme.css';
  1103. $view_mode = !empty($display['settings']['view_mode']) ? $display['settings']['view_mode'] : 'full';
  1104. foreach ($items as $delta => $item) {
  1105. if ($field_collection = field_collection_field_get_entity($item)) {
  1106. $element[$delta]['entity'] = $field_collection->view($view_mode);
  1107. $element[$delta]['#theme_wrappers'] = array('field_collection_view');
  1108. $element[$delta]['#attributes']['class'][] = 'field-collection-view';
  1109. $element[$delta]['#attributes']['class'][] = 'clearfix';
  1110. $element[$delta]['#attributes']['class'][] = drupal_clean_css_identifier('view-mode-' . $view_mode);
  1111. $links = array(
  1112. '#theme' => 'links__field_collection_view',
  1113. );
  1114. $links['#attributes']['class'][] = 'field-collection-view-links';
  1115. foreach (array('edit', 'delete') as $op) {
  1116. if ($settings[$op] && field_collection_item_access($op == 'edit' ? 'update' : $op, $field_collection)) {
  1117. $links['#links'][$op] = array(
  1118. 'title' => entity_i18n_string("field:{$field['field_name']}:{$instance['bundle']}:setting_$op", $settings[$op]),
  1119. 'href' => $field_collection->path() . '/' . $op,
  1120. 'query' => drupal_get_destination(),
  1121. );
  1122. }
  1123. }
  1124. $element[$delta]['links'] = $links;
  1125. }
  1126. }
  1127. field_collection_field_formatter_links($element, $entity_type, $entity, $field, $instance, $langcode, $items, $display);
  1128. break;
  1129. case 'field_collection_fields':
  1130. $view_mode = !empty($display['settings']['view_mode']) ? $display['settings']['view_mode'] : 'full';
  1131. foreach ($items as $delta => $item) {
  1132. if ($field_collection = field_collection_field_get_entity($item)) {
  1133. $element[$delta]['entity'] = $field_collection->view($view_mode);
  1134. }
  1135. }
  1136. break;
  1137. }
  1138. return $element;
  1139. }
  1140. /**
  1141. * Helper function to add links to a field collection field.
  1142. */
  1143. function field_collection_field_formatter_links(&$element, $entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  1144. $settings = $display['settings'];
  1145. if ($settings['add'] && ($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED || count($items) < $field['cardinality'])) {
  1146. // Check whether the current is allowed to create a new item.
  1147. $field_collection_item = entity_create('field_collection_item', array('field_name' => $field['field_name']));
  1148. $field_collection_item->setHostEntity($entity_type, $entity, LANGUAGE_NONE, FALSE);
  1149. if (field_collection_item_access('create', $field_collection_item)) {
  1150. $path = field_collection_field_get_path($field);
  1151. list($id) = entity_extract_ids($entity_type, $entity);
  1152. $element['#suffix'] = '';
  1153. if (!empty($settings['description'])) {
  1154. $element['#suffix'] .= '<div class="description field-collection-description">' . field_filter_xss($instance['description']) . '</div>';
  1155. }
  1156. $title = entity_i18n_string("field:{$field['field_name']}:{$instance['bundle']}:setting_add", $settings['add']);
  1157. $add_path = $path . '/add/' . $entity_type . '/' . $id;
  1158. $element['#suffix'] .= '<ul class="action-links action-links-field-collection-add"><li>';
  1159. $element['#suffix'] .= l($title, $add_path, array('query' => drupal_get_destination()));
  1160. $element['#suffix'] .= '</li></ul>';
  1161. }
  1162. }
  1163. // If there is no add link, add a special class to the last item.
  1164. if (empty($element['#suffix'])) {
  1165. $index = count(element_children($element)) - 1;
  1166. $element[$index]['#attributes']['class'][] = 'field-collection-view-final';
  1167. }
  1168. $element += array('#prefix' => '', '#suffix' => '');
  1169. $element['#prefix'] .= '<div class="field-collection-container clearfix">';
  1170. $element['#suffix'] .= '</div>';
  1171. return $element;
  1172. }
  1173. /**
  1174. * Themes field collection items printed using the field_collection_view formatter.
  1175. */
  1176. function theme_field_collection_view($variables) {
  1177. $element = $variables['element'];
  1178. return '<div' . drupal_attributes($element['#attributes']) . '>' . $element['#children'] . '</div>';
  1179. }
  1180. /**
  1181. * Implements hook_field_widget_info().
  1182. */
  1183. function field_collection_field_widget_info() {
  1184. return array(
  1185. 'field_collection_hidden' => array(
  1186. 'label' => t('Hidden'),
  1187. 'field types' => array('field_collection'),
  1188. 'behaviors' => array(
  1189. 'multiple values' => FIELD_BEHAVIOR_CUSTOM,
  1190. 'default value' => FIELD_BEHAVIOR_NONE,
  1191. ),
  1192. ),
  1193. 'field_collection_embed' => array(
  1194. 'label' => t('Embedded'),
  1195. 'field types' => array('field_collection'),
  1196. 'behaviors' => array(
  1197. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  1198. 'default value' => FIELD_BEHAVIOR_NONE,
  1199. ),
  1200. ),
  1201. );
  1202. }
  1203. /**
  1204. * Implements hook_field_widget_form().
  1205. */
  1206. function field_collection_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  1207. static $recursion = 0;
  1208. switch ($instance['widget']['type']) {
  1209. case 'field_collection_hidden':
  1210. return $element;
  1211. case 'field_collection_embed':
  1212. // If the field collection item form contains another field collection,
  1213. // we might ran into a recursive loop. Prevent that.
  1214. if ($recursion++ > 3) {
  1215. drupal_set_message(t('The field collection item form has not been embedded to avoid recursive loops.'), 'error');
  1216. return $element;
  1217. }
  1218. $field_parents = $element['#field_parents'];
  1219. $field_name = $element['#field_name'];
  1220. $language = $element['#language'];
  1221. // Nest the field collection item entity form in a dedicated parent space,
  1222. // by appending [field_name, langcode, delta] to the current parent space.
  1223. // That way the form values of the field collection item are separated.
  1224. $parents = array_merge($field_parents, array($field_name, $language, $delta));
  1225. $element += array(
  1226. '#element_validate' => array('field_collection_field_widget_embed_validate'),
  1227. '#parents' => $parents,
  1228. );
  1229. if ($field['cardinality'] == 1) {
  1230. $element['#type'] = 'fieldset';
  1231. }
  1232. $field_state = field_form_get_state($field_parents, $field_name, $language, $form_state);
  1233. if (!empty($field['settings']['hide_blank_items']) && $delta == $field_state['items_count'] && $delta > 0) {
  1234. // Do not add a blank item. Also see
  1235. // field_collection_field_attach_form() for correcting #max_delta.
  1236. $recursion--;
  1237. return FALSE;
  1238. }
  1239. elseif (!empty($field['settings']['hide_blank_items']) && $field_state['items_count'] == 0) {
  1240. // We show one item, so also specify that as item count. So when the
  1241. // add button is pressed the item count will be 2 and we show to items.
  1242. $field_state['items_count'] = 1;
  1243. }
  1244. if (isset($field_state['entity'][$delta])) {
  1245. $field_collection_item = $field_state['entity'][$delta];
  1246. }
  1247. else {
  1248. if (isset($items[$delta])) {
  1249. $field_collection_item = field_collection_field_get_entity($items[$delta], $field_name);
  1250. }
  1251. // Show an empty collection if we have no existing one or it does not
  1252. // load.
  1253. if (empty($field_collection_item)) {
  1254. $field_collection_item = entity_create('field_collection_item', array('field_name' => $field_name));
  1255. }
  1256. // Put our entity in the form state, so FAPI callbacks can access it.
  1257. $field_state['entity'][$delta] = $field_collection_item;
  1258. }
  1259. field_form_set_state($field_parents, $field_name, $language, $form_state, $field_state);
  1260. field_attach_form('field_collection_item', $field_collection_item, $element, $form_state, $language);
  1261. if (empty($element['#required'])) {
  1262. $element['#after_build'][] = 'field_collection_field_widget_embed_delay_required_validation';
  1263. }
  1264. if ($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED) {
  1265. $element['remove_button'] = array(
  1266. '#delta' => $delta,
  1267. '#name' => implode('_', $parents) . '_remove_button',
  1268. '#type' => 'submit',
  1269. '#value' => t('Remove'),
  1270. '#validate' => array(),
  1271. '#submit' => array('field_collection_remove_submit'),
  1272. '#limit_validation_errors' => array(),
  1273. '#ajax' => array(
  1274. 'path' => 'field_collection/ajax',
  1275. 'effect' => 'fade',
  1276. ),
  1277. '#weight' => 1000,
  1278. );
  1279. }
  1280. $recursion--;
  1281. return $element;
  1282. }
  1283. }
  1284. /**
  1285. * Implements hook_field_attach_form().
  1286. *
  1287. * Corrects #max_delta when we hide the blank field collection item.
  1288. *
  1289. * @see field_add_more_js()
  1290. * @see field_collection_field_widget_form()
  1291. */
  1292. function field_collection_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
  1293. foreach (field_info_instances($entity_type, $form['#bundle']) as $field_name => $instance) {
  1294. $field = field_info_field($field_name);
  1295. if ($field['type'] == 'field_collection' && $field['settings']['hide_blank_items']
  1296. && field_access('edit', $field, $entity_type) && $instance['widget']['type'] == 'field_collection_embed') {
  1297. $element_langcode = $form[$field_name]['#language'];
  1298. if ($form[$field_name][$element_langcode]['#max_delta'] > 0) {
  1299. $form[$field_name][$element_langcode]['#max_delta']--;
  1300. }
  1301. }
  1302. }
  1303. }
  1304. /**
  1305. * Page callback to handle AJAX for removing a field collection item.
  1306. *
  1307. * This is a direct page callback. The actual job of deleting the item is
  1308. * done in the submit handler for the button, so all we really need to
  1309. * do is process the form and then generate output. We generate this
  1310. * output by doing a replace command on the id of the entire form element.
  1311. */
  1312. function field_collection_remove_js() {
  1313. // drupal_html_id() very helpfully ensures that all html IDS are unique
  1314. // on a page. Unfortunately what it doesn't realize is that the IDs
  1315. // we are generating are going to replace IDs that already exist, so
  1316. // this actually works against us.
  1317. if (isset($_POST['ajax_html_ids'])) {
  1318. unset($_POST['ajax_html_ids']);
  1319. }
  1320. list($form, $form_state) = ajax_get_form();
  1321. drupal_process_form($form['#form_id'], $form, $form_state);
  1322. // Get the information on what we're removing.
  1323. $button = $form_state['triggering_element'];
  1324. // Go two levels up in the form, to the whole widget.
  1325. $element = drupal_array_get_nested_value($form, array_slice($button['#array_parents'], 0, -3));
  1326. // Now send back the proper AJAX command to replace it.
  1327. $return = array(
  1328. '#type' => 'ajax',
  1329. '#commands' => array(
  1330. ajax_command_replace('#' . $element['#id'], drupal_render($element))
  1331. ),
  1332. );
  1333. // Because we're doing this ourselves, messages aren't automatic. We have
  1334. // to add them.
  1335. $messages = theme('status_messages');
  1336. if ($messages) {
  1337. $return['#commands'][] = ajax_command_prepend('#' . $element['#id'], $messages);
  1338. }
  1339. return $return;
  1340. }
  1341. /**
  1342. * Submit callback to remove an item from the field UI multiple wrapper.
  1343. *
  1344. * When a remove button is submitted, we need to find the item that it
  1345. * referenced and delete it. Since field UI has the deltas as a straight
  1346. * unbroken array key, we have to renumber everything down. Since we do this
  1347. * we *also* need to move all the deltas around in the $form_state['values']
  1348. * and $form_state['input'] so that user changed values follow. This is a bit
  1349. * of a complicated process.
  1350. */
  1351. function field_collection_remove_submit($form, &$form_state) {
  1352. $button = $form_state['triggering_element'];
  1353. $delta = $button['#delta'];
  1354. // Where in the form we'll find the parent element.
  1355. $address = array_slice($button['#array_parents'], 0, -2);
  1356. // Go one level up in the form, to the widgets container.
  1357. $parent_element = drupal_array_get_nested_value($form, $address);
  1358. $field_name = $parent_element['#field_name'];
  1359. $langcode = $parent_element['#language'];
  1360. $parents = $parent_element['#field_parents'];
  1361. $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
  1362. // Go ahead and renumber everything from our delta to the last
  1363. // item down one. This will overwrite the item being removed.
  1364. for ($i = $delta; $i <= $field_state['items_count']; $i++) {
  1365. $old_element_address = array_merge($address, array($i + 1));
  1366. $new_element_address = array_merge($address, array($i));
  1367. $moving_element = drupal_array_get_nested_value($form, $old_element_address);
  1368. $moving_element_value = drupal_array_get_nested_value($form_state['values'], $old_element_address);
  1369. $moving_element_input = drupal_array_get_nested_value($form_state['input'], $old_element_address);
  1370. // Tell the element where it's being moved to.
  1371. $moving_element['#parents'] = $new_element_address;
  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. // 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. // Replace the deleted entity with an empty one. This helps to ensure that
  1384. // trying to add a new entity won't ressurect a deleted entity from the
  1385. // trash bin.
  1386. $count = count($field_state['entity']);
  1387. $field_state['entity'][$count] = entity_create('field_collection_item', array('field_name' => $field_name));
  1388. // Then remove the last item. But we must not go negative.
  1389. if ($field_state['items_count'] > 0) {
  1390. $field_state['items_count']--;
  1391. }
  1392. // Fix the weights. Field UI lets the weights be in a range of
  1393. // (-1 * item_count) to (item_count). This means that when we remove one,
  1394. // the range shrinks; weights outside of that range then get set to
  1395. // the first item in the select by the browser, floating them to the top.
  1396. // We use a brute force method because we lost weights on both ends
  1397. // and if the user has moved things around, we have to cascade because
  1398. // if I have items weight weights 3 and 4, and I change 4 to 3 but leave
  1399. // the 3, the order of the two 3s now is undefined and may not match what
  1400. // the user had selected.
  1401. $input = drupal_array_get_nested_value($form_state['input'], $address);
  1402. // Sort by weight
  1403. uasort($input, '_field_sort_items_helper');
  1404. // Reweight everything in the correct order.
  1405. $weight = -1 * $field_state['items_count'];
  1406. foreach ($input as $key => $item) {
  1407. if ($item) {
  1408. $input[$key]['_weight'] = $weight++;
  1409. }
  1410. }
  1411. drupal_array_set_nested_value($form_state['input'], $address, $input);
  1412. field_form_set_state($parents, $field_name, $langcode, $form_state, $field_state);
  1413. $form_state['rebuild'] = TRUE;
  1414. }
  1415. /**
  1416. * Gets a field collection item entity for a given field item.
  1417. *
  1418. * @param $field_name
  1419. * (optional) If given and there is no entity yet, a new entity object is
  1420. * created for the given item.
  1421. *
  1422. * @return
  1423. * The entity object or FALSE.
  1424. */
  1425. function field_collection_field_get_entity(&$item, $field_name = NULL) {
  1426. if (isset($item['entity'])) {
  1427. return $item['entity'];
  1428. }
  1429. elseif (isset($item['value'])) {
  1430. // By default always load the default revision, so caches get used.
  1431. $entity = field_collection_item_load($item['value']);
  1432. if ($entity->revision_id != $item['revision_id']) {
  1433. // A non-default revision is a referenced, so load this one.
  1434. $entity = field_collection_item_revision_load($item['revision_id']);
  1435. }
  1436. return $entity;
  1437. }
  1438. elseif (!isset($item['entity']) && isset($field_name)) {
  1439. $item['entity'] = entity_create('field_collection_item', array('field_name' => $field_name));
  1440. return $item['entity'];
  1441. }
  1442. return FALSE;
  1443. }
  1444. /**
  1445. * FAPI #after_build of an individual field collection element to delay the validation of #required.
  1446. */
  1447. function field_collection_field_widget_embed_delay_required_validation(&$element, &$form_state) {
  1448. // If the process_input flag is set, the form and its input is going to be
  1449. // validated. Prevent #required (sub)fields from throwing errors while
  1450. // their non-#required field collection item is empty.
  1451. if ($form_state['process_input']) {
  1452. _field_collection_collect_required_elements($element, $element['#field_collection_required_elements']);
  1453. }
  1454. return $element;
  1455. }
  1456. function _field_collection_collect_required_elements(&$element, &$required_elements) {
  1457. // Recurse through all children.
  1458. foreach (element_children($element) as $key) {
  1459. if (isset($element[$key]) && $element[$key]) {
  1460. _field_collection_collect_required_elements($element[$key], $required_elements);
  1461. }
  1462. }
  1463. if (!empty($element['#required'])) {
  1464. $element['#required'] = FALSE;
  1465. $required_elements[] = &$element;
  1466. $element += array('#pre_render' => array());
  1467. array_unshift($element['#pre_render'], 'field_collection_field_widget_render_required');
  1468. }
  1469. }
  1470. /**
  1471. * #pre_render callback that ensures the element is rendered as being required.
  1472. */
  1473. function field_collection_field_widget_render_required($element) {
  1474. $element['#required'] = TRUE;
  1475. return $element;
  1476. }
  1477. /**
  1478. * FAPI validation of an individual field collection element.
  1479. */
  1480. function field_collection_field_widget_embed_validate($element, &$form_state, $complete_form) {
  1481. $instance = field_widget_instance($element, $form_state);
  1482. $field = field_widget_field($element, $form_state);
  1483. $field_parents = $element['#field_parents'];
  1484. $field_name = $element['#field_name'];
  1485. $language = $element['#language'];
  1486. $field_state = field_form_get_state($field_parents, $field_name, $language, $form_state);
  1487. $field_collection_item = $field_state['entity'][$element['#delta']];
  1488. // Attach field API validation of the embedded form.
  1489. field_attach_form_validate('field_collection_item', $field_collection_item, $element, $form_state);
  1490. // Now validate required elements if the entity is not empty.
  1491. if (!field_collection_item_is_empty($field_collection_item) && !empty($element['#field_collection_required_elements'])) {
  1492. foreach ($element['#field_collection_required_elements'] as &$elements) {
  1493. // Copied from _form_validate().
  1494. if (isset($elements['#needs_validation'])) {
  1495. $is_empty_multiple = (!count($elements['#value']));
  1496. $is_empty_string = (is_string($elements['#value']) && drupal_strlen(trim($elements['#value'])) == 0);
  1497. $is_empty_value = ($elements['#value'] === 0);
  1498. if ($is_empty_multiple || $is_empty_string || $is_empty_value) {
  1499. if (isset($elements['#title'])) {
  1500. form_error($elements, t('!name field is required.', array('!name' => $elements['#title'])));
  1501. }
  1502. else {
  1503. form_error($elements);
  1504. }
  1505. }
  1506. }
  1507. }
  1508. }
  1509. // Only if the form is being submitted, finish the collection entity and
  1510. // prepare it for saving.
  1511. if ($form_state['submitted'] && !form_get_errors()) {
  1512. field_attach_submit('field_collection_item', $field_collection_item, $element, $form_state);
  1513. // Load initial form values into $item, so any other form values below the
  1514. // same parents are kept.
  1515. $item = drupal_array_get_nested_value($form_state['values'], $element['#parents']);
  1516. // Set the _weight if it is a multiple field.
  1517. if (isset($element['_weight']) && ($field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED)) {
  1518. $item['_weight'] = $element['_weight']['#value'];
  1519. }
  1520. // Put the field collection item in $item['entity'], so it is saved with
  1521. // the host entity via hook_field_presave() / field API if it is not empty.
  1522. // @see field_collection_field_presave()
  1523. $item['entity'] = $field_collection_item;
  1524. form_set_value($element, $item, $form_state);
  1525. }
  1526. }
  1527. /**
  1528. * Implements hook_field_create_field().
  1529. */
  1530. function field_collection_field_create_field($field) {
  1531. if ($field['type'] == 'field_collection') {
  1532. field_attach_create_bundle('field_collection_item', $field['field_name']);
  1533. // Clear caches.
  1534. entity_info_cache_clear();
  1535. // Do not directly issue menu rebuilds here to avoid potentially multiple
  1536. // rebuilds. Instead, let menu_get_item() issue the rebuild on the next
  1537. // request.
  1538. variable_set('menu_rebuild_needed', TRUE);
  1539. }
  1540. }
  1541. /**
  1542. * Implements hook_field_delete_field().
  1543. */
  1544. function field_collection_field_delete_field($field) {
  1545. if ($field['type'] == 'field_collection') {
  1546. // Notify field.module that field collection was deleted.
  1547. field_attach_delete_bundle('field_collection_item', $field['field_name']);
  1548. // Clear caches.
  1549. entity_info_cache_clear();
  1550. // Do not directly issue menu rebuilds here to avoid potentially multiple
  1551. // rebuilds. Instead, let menu_get_item() issue the rebuild on the next
  1552. // request.
  1553. variable_set('menu_rebuild_needed', TRUE);
  1554. }
  1555. }
  1556. /**
  1557. * Implements hook_i18n_string_list_{textgroup}_alter().
  1558. */
  1559. function field_collection_i18n_string_list_field_alter(&$properties, $type, $instance) {
  1560. if ($type == 'field_instance') {
  1561. $field = field_info_field($instance['field_name']);
  1562. if ($field['type'] == 'field_collection' && !empty($instance['display'])) {
  1563. foreach ($instance['display'] as $view_mode => $display) {
  1564. if ($display['type'] != 'field_collection_fields') {
  1565. $display['settings'] += array('edit' => 'edit', 'delete' => 'delete', 'add' => 'add');
  1566. $properties['field'][$instance['field_name']][$instance['bundle']]['setting_edit'] = array(
  1567. 'title' => t('Edit link title'),
  1568. 'string' => $display['settings']['edit'],
  1569. );
  1570. $properties['field'][$instance['field_name']][$instance['bundle']]['setting_delete'] = array(
  1571. 'title' => t('Delete link title'),
  1572. 'string' => $display['settings']['delete'],
  1573. );
  1574. $properties['field'][$instance['field_name']][$instance['bundle']]['setting_add'] = array(
  1575. 'title' => t('Add link title'),
  1576. 'string' => $display['settings']['add'],
  1577. );
  1578. }
  1579. }
  1580. }
  1581. }
  1582. }
  1583. /**
  1584. * Implements hook_views_api().
  1585. */
  1586. function field_collection_views_api() {
  1587. return array(
  1588. 'api' => '3.0-alpha1',
  1589. 'path' => drupal_get_path('module', 'field_collection') . '/views',
  1590. );
  1591. }
  1592. /**
  1593. * Implements hook_features_pipe_component_alter() for fields.
  1594. */
  1595. function field_collection_features_pipe_field_alter(&$pipe, $data, $export) {
  1596. // Add the fields of the field collection entity to the pipe.
  1597. foreach ($data as $identifier) {
  1598. if (($field = features_field_load($identifier)) && $field['field_config']['type'] == 'field_collection') {
  1599. $fields = field_info_instances('field_collection_item', $field['field_config']['field_name']);
  1600. foreach ($fields as $name => $field) {
  1601. $pipe['field'][] = "{$field['entity_type']}-{$field['bundle']}-{$field['field_name']}";
  1602. }
  1603. }
  1604. }
  1605. }
  1606. /**
  1607. * Callback for generating entity metadata property info for our field instances.
  1608. *
  1609. * @see field_collection_field_info()
  1610. */
  1611. function field_collection_entity_metadata_property_callback(&$info, $entity_type, $field, $instance, $field_type) {
  1612. $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$field['field_name']];
  1613. // Set the bundle as we know it is the name of the field.
  1614. $property['bundle'] = $field['field_name'];
  1615. $property['getter callback'] = 'field_collection_field_property_get';
  1616. }
  1617. /**
  1618. * Entity property info setter callback for the host entity property.
  1619. *
  1620. * As the property is of type entity, the value will be passed as a wrapped
  1621. * entity.
  1622. */
  1623. function field_collection_item_set_host_entity($item, $property_name, $wrapper) {
  1624. if (empty($item->is_new)) {
  1625. throw new EntityMetadataWrapperException('The host entity may be set only during creation of a field collection item.');
  1626. }
  1627. if (!isset($wrapper->{$item->field_name})) {
  1628. throw new EntityMetadataWrapperException('The specified entity has no such field collection field.');
  1629. }
  1630. $item->setHostEntity($wrapper->type(), $wrapper->value());
  1631. }
  1632. /**
  1633. * Entity property info getter callback for the host entity property.
  1634. */
  1635. function field_collection_item_get_host_entity($item) {
  1636. // As the property is defined as 'entity', we have to return a wrapped entity.
  1637. return entity_metadata_wrapper($item->hostEntityType(), $item->hostEntity());
  1638. }
  1639. /**
  1640. * Entity property info getter callback for the field collection items.
  1641. *
  1642. * Like entity_metadata_field_property_get(), but additionally supports getting
  1643. * not-yet saved collection items from @code $item['entity'] @endcode.
  1644. */
  1645. function field_collection_field_property_get($entity, array $options, $name, $entity_type, $info) {
  1646. $field = field_info_field($name);
  1647. $langcode = field_language($entity_type, $entity, $name, isset($options['language']) ? $options['language']->language : NULL);
  1648. $values = array();
  1649. if (isset($entity->{$name}[$langcode])) {
  1650. foreach ($entity->{$name}[$langcode] as $delta => $data) {
  1651. // Wrappers do not support multiple entity references being revisions or
  1652. // not yet saved entities. In the case of a single reference we can return
  1653. // the entity object though.
  1654. if ($field['cardinality'] == 1) {
  1655. $values[$delta] = field_collection_field_get_entity($data);
  1656. }
  1657. elseif (isset($data['value'])) {
  1658. $values[$delta] = $data['value'];
  1659. }
  1660. }
  1661. }
  1662. // For an empty single-valued field, we have to return NULL.
  1663. return $field['cardinality'] == 1 ? ($values ? reset($values) : NULL) : $values;
  1664. }
  1665. /**
  1666. * Implements hook_devel_generate().
  1667. */
  1668. function field_collection_devel_generate($object, $field, $instance, $bundle) {
  1669. // Create a new field collection object and add fake data to its fields.
  1670. $field_collection = entity_create('field_collection_item', array('field_name' => $field['field_name']));
  1671. $field_collection->language = $object->language;
  1672. $field_collection->setHostEntity($instance['entity_type'], $object, $object->language, FALSE);
  1673. devel_generate_fields($field_collection, 'field_collection_item', $field['field_name']);
  1674. $field_collection->save(TRUE);
  1675. return array('value' => $field_collection->item_id);
  1676. }