Skip to content

Instantly share code, notes, and snippets.

@heitoralthmann
Last active July 11, 2023 09:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save heitoralthmann/9fc67f34441564ae29b6d889d87e96b7 to your computer and use it in GitHub Desktop.
Save heitoralthmann/9fc67f34441564ae29b6d889d87e96b7 to your computer and use it in GitHub Desktop.
Drupal 8 - Resizing field with existing data - Change text field max length
<?php
//
// ATTENTION!
// This method of resizing field data TRUNCATES the information present in the field.
// This is heavily based on the solution available at https://github.com/evolvingweb/custom_field_resize
// with only a minor tweak to truncate field data before resizing the field, so we don't get an SQL error.
//
/**
* Shrink the length of "field_short_title" to 45 characters.
*/
function module_name_update_8001() {
// Prepare relevant variables.
$entity_type = 'paragraph';
$field_name = 'field_short_title';
$field_length = 45;
// Update database schema.
$database = \Drupal::database();
// Resize the main field data table.
$database->query("UPDATE {$entity_type}__{$field_name} SET field_short_title_value = LEFT(RTRIM(field_short_title_value), {$field_length});");
$database->query("ALTER TABLE {$entity_type}__{$field_name} MODIFY {$field_name}_value VARCHAR({$field_length})");
// Resize the revision field data table (if revisions are enabled).
$database->query("UPDATE {$entity_type}_revision__{$field_name} SET field_short_title_value = LEFT(RTRIM(field_short_title_value), {$field_length});");
$database->query("ALTER TABLE {$entity_type}_revision__{$field_name} MODIFY {$field_name}_value VARCHAR({$field_length})");
// Update storage schema.
$storage_key = $entity_type . '.field_schema_data.' . $field_name;
$storage_schema = \Drupal::keyValue('entity.storage_schema.sql');
$field_schema = $storage_schema->get($storage_key);
$field_schema[$entity_type . '__' . $field_name]['fields'][$field_name . '_value']['length'] = $field_length;
$field_schema[$entity_type . '_revision__' . $field_name]['fields'][$field_name . '_value']['length'] = $field_length;
$storage_schema->set($storage_key, $field_schema);
// Update field configuration.
$config = \Drupal::configFactory()
->getEditable("field.storage.{$entity_type}.{$field_name}");
$config->set('settings.max_length', $field_length);
$config->save(TRUE);
// Update field storage configuration.
FieldStorageConfig::loadByName($entity_type, $field_name)->save();
return t('Length of @entity-type.@field-name was updated to @field-length', [
'@entity-type' => $entity_type,
'@field-name' => $field_name,
'@field-length' => $field_length,
]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment