field_collection.module 70 KB

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