How to Increase Field Length with Existing Data
">
How to Increase Field Length with Existing Data
To change an existing fields length if the field has data in it, you need to alter the database tables for the field and the config storage for the field, do this in a hook update as shown below.
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Core\Field\BaseFieldDefinition;
function hook_update_8001() {
$database = \Drupal::database();
$database->query("ALTER TABLE node__your_custom_field MODIFY your_custom_field_value VARCHAR(100)");
$database->query("ALTER TABLE node_revision__your_custom_field MODIFY your_custom_field_value VARCHAR(100)");
$storage_key = 'node.field_schema_data.your_custom_field';
$storage_schema = \Drupal::keyValue('entity.storage_schema.sql');
$field_schema = $storage_schema->get($storage_key);
$field_schema['node__your_custom_field']['fields']['your_custom_field_value']['length'] = 100;
$field_schema['node_revision__your_custom_field']['fields']['your_custom_field_value']['length'] = 100;
$storage_schema->set($storage_key, $field_schema);
// Update field configuration.
$config = \Drupal::configFactory()
->getEditable('field.storage.node.your_custom_field');
$config->set('settings.max_length', 100);
$config->save(TRUE);
// Update field storage configuration.
FieldStorageConfig::loadByName('node', 'your_custom_field')->save();
}