Skip to main content
4 of 5
fixed grammar
avpaderno
  • 97.9k
  • 15
  • 164
  • 284

field_purge_field() is described as follows:

This function assumes all data for the field has already been purged and should only be called by field_purge_batch().

On Drupal, fields are effectively removed during cron tasks; in fact, field_purge_batch() is called from field_cron(), the implementation of hook_cron() done from the Field module. There is no need for you to call neither field_purge_field() nor field_purge_batch().

If you want to write code to purge fields for a node bundle, that code would be similar to the following one. (See the notes after the code, thought.)

  $properties = array(
    'entity_type' => 'node',
    'bundle' => 'Your bundle (a.k.a. content type)',
    'include_deleted' => TRUE,
  );

  $fields = \Drupal::entityManager()->getStorage('field_config')->loadByProperties($properties);

  $info = \Drupal::entityManager()->getDefinitions();
  foreach ($fields as $field) {
    $entity_type = $field->getTargetEntityTypeId();

    // Proceed only if the module implementing the entity has not been uninstalled already.
    if (isset($info[$entity_type])) {
      Drupal::entityManager()->getStorage($entity_type)->purgeFieldData($field, 100);
      field_purge_field($field);
    }
  }

Notes

  • Purging the fields is thought to be ran during cron tasks; that is why Drupal::entityManager()->getStorage()->purgeFieldData() requires the batch size as argument. I used a value of 100, which would possibly allow the code to purge all the fields for that content type, but it could also cause a PHP timeout error. It would be better to run the code from PHP CLI, in order to avoid any execution time out.
  • You should not need to use this code; in most of the cases, you should execute the cron tasks (which is when Drupal purges the fields of a deleted bundle), or use Drush to purge the fields, either running hook_cron() with it, or executing a specific Drush command (if it exists).

As for truncating the tables, that is the wrong way to proceed. It would not allow Drupal and third-party modules to delete the data they have for the fields; even if you know which tables Drupal uses, you could forget a table used by third-party modules.

avpaderno
  • 97.9k
  • 15
  • 164
  • 284