Last active
November 1, 2016 13:37
-
-
Save tstoeckler/5c7997b12575c472a8c0a25a9e599cfe to your computer and use it in GitHub Desktop.
Drupal 8: Empty all field values of a specific field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @file | |
* This file deletes all field values of a specific field. | |
* | |
* It is meant to be run with 'drush php-script'. | |
* | |
* It is useful if you want to delete all data from a field, | |
* for example to change field storage settings of a configurable | |
* field, without deleting the actual entities. | |
*/ | |
// Change these according to your use-case. | |
$entity_type_id = 'node'; | |
$field_name = 'body'; | |
/** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */ | |
$storage = \Drupal::entityTypeManager()->getStorage($entity_type_id); | |
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */ | |
foreach ($storage->loadMultiple() as $entity) { | |
$changed = FALSE; | |
/** @var \Drupal\Core\Language\LanguageInterface $language */ | |
foreach ($entity->getTranslationLanguages(TRUE) as $language) { | |
$translation = $entity->getTranslation($language->getId()); | |
$items = $translation->get($field_name); | |
if (!$items->isEmpty()) { | |
$items->setValue([]); | |
$changed = TRUE; | |
} | |
} | |
if ($changed) { | |
$entity->save(); | |
} | |
} | |
$revision_ids = array_keys($storage->getQuery()->allRevisions()->execute()); | |
foreach ($revision_ids as $revision_id) { | |
/** @var \Drupal\Core\Entity\ContentEntityInterface $revision */ | |
$revision = $storage->loadRevision($revision_id); | |
if (!$revision->get($field_name)->isEmpty()) { | |
$storage->deleteRevision($revision_id); | |
} | |
$changed = FALSE; | |
/** @var \Drupal\Core\Language\LanguageInterface $language */ | |
foreach ($revision->getTranslationLanguages(TRUE) as $language) { | |
$translation = $revision->getTranslation($language->getId()); | |
$items = $translation->get($field_name); | |
if (!$translation->get($field_name)->isEmpty()) { | |
$storage->deleteRevision($revision_id); | |
continue 2; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment