-
-
Save thelebster/98a1f602730b404a43040c56f249f493 to your computer and use it in GitHub Desktop.
Drupal 8 - Resizing field with existing data - Change text field max length
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 | |
// | |
// 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