field_collection.module 73 KB

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