Skip to content

Instantly share code, notes, and snippets.

@theodorosploumis
Last active June 6, 2024 08:39
Show Gist options
  • Save theodorosploumis/78376edd2663b765311f83b48a2ac8fc to your computer and use it in GitHub Desktop.
Save theodorosploumis/78376edd2663b765311f83b48a2ac8fc to your computer and use it in GitHub Desktop.
Drupal 10.x - Update text_format of all the wysiwyg fields in bulk (drush script)
<?php
// phpcs:ignoreFile
// Update text_format of all the wysiwyg fields.
// Exec with drush: "drush scr upgrade_html5_text_format.php"
// Change values according to your needs.
$old_format = "html";
$new_format = "html5";
$field_type = "text_long";
$entity_types = [
"node",
"block_content",
"paragraph",
"taxonomy_term",
];
// Normally, you should not edit below this line.
$fields = [];
$unique_fields = [];
$bundle_names = [];
$database = \Drupal::database();
// Get entity bundles
foreach ($entity_types as $type) {
$bundles = \Drupal::service('entity_type.bundle.info')->getBundleInfo($type);
$machine_names = array_keys($bundles);
$bundle_names[$type] = $machine_names;
}
// Get all custom fields that are "text_long" fields.
foreach ($bundle_names as $type => $machine_names) {
foreach ($machine_names as $machine_name) {
$bundle_fields = \Drupal::service('entity_field.manager')->getFieldDefinitions($type, $machine_name);
foreach ($bundle_fields as $field_name => $field) {
$current_field_type = $field->getFieldStorageDefinition()->getType();
if (str_starts_with($field_name, "field_") && $current_field_type === $field_type) {
$fields[$type][] = $field_name;
}
// Add "body" core field
if (str_starts_with($field_name, "body") && $current_field_type === $field_type) {
$fields[$type][] = $field_name;
}
// Add "description" core field
if (str_starts_with($field_name, "description") && $current_field_type === $field_type) {
$fields[$type][] = $field_name;
}
}
}
if (isset($fields[$type])) {
$unique_fields[$type] = array_unique($fields[$type]);
}
}
// Alter field tables
foreach ($unique_fields as $type => $fields) {
foreach ($fields as $field) {
$tables = [
$type . "__" . $field,
$type . "_revision__" . $field,
];
$column = $field . "_format";
foreach ($tables as $table) {
$update_field = $database->update($table)
->condition($column, $old_format, "=")
->fields([$column => $new_format])
->execute();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment