Skip to content

Instantly share code, notes, and snippets.

@MatthieuScarset
Created April 16, 2024 15:41
Show Gist options
  • Save MatthieuScarset/b613348ea8f261358693f6cb6bf125fc to your computer and use it in GitHub Desktop.
Save MatthieuScarset/b613348ea8f261358693f6cb6bf125fc to your computer and use it in GitHub Desktop.
Drupal - Hook update to copy values from one field to another - runs after config import
<?php
// drush updb ; trigger expection so the update don't pass.
// drush cim ; import your new field.
// drush updb ; the hook update is successfull and values are copied.
/**
* Populate formatted texts from previous field on paragraph callout.
*/
function mymodule_update_10103(&$sandbox): void {
$source_field = 'field_text_txtpl';
$target_field = 'field_content_txtfl';
$fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('paragraph', 'callout');
$field_exists = array_filter($fields, function($field_name) use ($target_field) {
return $field_name == $target_field;
}, ARRAY_FILTER_USE_KEY);
if (empty($field_exists)) {
throw new \Exception('Target field does not exist already.');
}
$storage = \Drupal::entityTypeManager()->getStorage('paragraph');
$paragraphs = $storage->loadByProperties(['type' => 'callout']);
$langcodes = array_map(function($language) {
/** @var \Drupal\Core\Language\LanguageInterface */
return $language->getId();
}, \Drupal::languageManager()->getLanguages());
/** @var \Drupal\paragraph\Entity\ParagraphInterface $paragraph */
foreach ($paragraphs as $paragraph) {
if ($paragraph->hasField($source_field) && $paragraph->hasField($target_field)) {
$paragraph->set($target_field, $paragraph->get($source_field)->getValue());
$paragraph->save();
}
foreach ($langcodes as $langcode) {
if ($paragraph->hasTranslation($langcode)) {
$trans = $paragraph->getTranslation($langcode);
if ($trans->hasField($source_field) && $trans->hasField($target_field)) {
$trans->set($target_field, $trans->get($source_field)->getValue());
$trans->save();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment