Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

in this post, I'll show you how to increase the length of field without losing data in drupal 8.

Question

How to increase the length of field to 255 without losing data.

resize field

Solution

use hook_update_N() to chnage the length of field to 255 in database, configuration, and in storage schema. like the example below.

mymodule.install

<?php

use Drupal\field\Entity\FieldStorageConfig;

/**
 * @param $sandbox
 */
function mymodule_update_90005(&$sandbox) {
  $entity_type = 'node';
  $field_name = 'field_description';
  $field_length = 255;

  $database = \Drupal::database();
  // Resize the main field data table.
  $database->query("ALTER TABLE {$entity_type}__{$field_name} MODIFY {$field_name}_value VARCHAR({$field_length})");
  // Resize the revision field data table.
  $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 updated to @field-length', [
    '@entity-type' => $entity_type,
    '@field-name' => $field_name,
    '@field-length' => $field_length,
  ]);
}

 

resized field

 

Comments

Submitted by Justin (not verified) on Fri, 12/13/2019 - 17:25 Permalink

I tried this out, but I'm still getting an error when i run my update saying that data exists. > [error] The SQL storage cannot change the schema for an existing field (field_special_information in product_entity entity) with data. It's in a custom entity, so I don't know if that is somehow making a difference.
Add new comment

Restricted HTML

Riadh Rahmi

Senior Web Developer (Drupal & Laravel)

I am a senior web developer, I have experience in planning and developing large scale dynamic web applications especially in Drupal and Laravel.

Web Posts

Search

Page Facebook