replicate_paragraphs.module 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * @file
  4. * Main methods of Replicate paragraphs module.
  5. */
  6. /**
  7. * Implements hook_replicate_entity_ENTITY_TYPE().
  8. */
  9. function replicate_paragraphs_replicate_entity_paragraphs_item(&$entity) {
  10. $entity->item_id = NULL;
  11. }
  12. /**
  13. * Implements hook_replicate_field_FIELD_TYPE().
  14. */
  15. function replicate_paragraphs_replicate_field_paragraphs(&$entity, $entity_type, $field_name) {
  16. foreach ($entity->$field_name as $language => $values) {
  17. replicate_paragraphs_clone_items($entity, $entity_type, $field_name, $language);
  18. }
  19. }
  20. /**
  21. * Implements hook_help().
  22. */
  23. function replicate_paragraphs_help($path, $arg) {
  24. switch ($path) {
  25. case 'admin/help#replicate_paragraphs_item':
  26. // Return a line-break version of the module README.txt.
  27. return check_markup(file_get_contents(dirname(__FILE__) . "/README.txt"));
  28. }
  29. }
  30. /**
  31. * Replicate a paragraphs field.
  32. *
  33. * @param object $entity
  34. * Entity to be modified.
  35. * @param string $entity_type
  36. * Entity type.
  37. * @param string $field_name
  38. * Name of the field.
  39. * @param string $language
  40. * Language of the field.
  41. */
  42. function replicate_paragraphs_clone_items(&$entity, $entity_type, $field_name, $language = LANGUAGE_NONE) {
  43. // Reset the field_language static.
  44. // If we don't, the language returned by field_language()
  45. // is FALSE, resulting in de metadata-wrapper (or field_get_items())
  46. // to get a FALSE / an empty array,
  47. // which means that the fields in it won't be cloned.
  48. drupal_static_reset('field_language');
  49. $entity_wrapper = entity_metadata_wrapper($entity_type, $entity);
  50. $old_items = $entity_wrapper->{$field_name}->value();
  51. if (is_null($old_items)) {
  52. $old_items = array();
  53. }
  54. elseif (!is_array($old_items)) {
  55. $old_items = array($old_items);
  56. }
  57. // Clean the previous entities from the field, so the new
  58. // can be saved instead.
  59. unset($entity->{$field_name}[$language]);
  60. foreach ($old_items as $old_item) {
  61. if (!empty($old_item)) {
  62. $new_item = replicate_clone_entity('paragraphs_item', $old_item);
  63. $new_item->setHostEntity($entity_type, $entity);
  64. // Don't save the new paragraphs,
  65. // it will be saved along with the host entity.
  66. }
  67. }
  68. }