Skip to content

Instantly share code, notes, and snippets.

@jmolivas
Last active December 4, 2017 16:52
Show Gist options
  • Save jmolivas/30c1e36b85eb48ff44dfb7d68c78f682 to your computer and use it in GitHub Desktop.
Save jmolivas/30c1e36b85eb48ff44dfb7d68c78f682 to your computer and use it in GitHub Desktop.
Change the text field maximum length
<?php
/**
* Update the length of a text field which already contains data.
*
* @param string $entity_type_id
* @param string $field_name
* @param integer $new_length
*/
function _module_change_text_field_max_length ($entity_type_id, $field_name, $new_length) {
$name = 'field.storage.' . $entity_type_id . "." . $field_name;
// Get the current settings
$result = \Drupal::database()->query(
'SELECT data FROM {config} WHERE name = :name',
[':name' => $name]
)->fetchField();
$data = unserialize($result);
$data['settings']['max_length'] = $new_length;
// Write settings back to the database.
\Drupal::database()->update('config')
->fields(array( 'data' => serialize($data)))
->condition('name', $name)
->execute();
// Update the value column in both the _data and _revision tables for the field
$table = $entity_type_id . "__" . $field_name;
$table_revision = $entity_type_id . "_revision__" . $field_name;
$new_field = ['type' => 'varchar', 'length' => $new_length];
$col_name = $field_name . '_value';
\Drupal::database()->schema()->changeField($table, $col_name, $col_name, $new_field);
\Drupal::database()->schema()->changeField($table_revision, $col_name, $col_name, $new_field);
// Flush the caches.
drupal_flush_all_caches();
}
function module_name_update_N(&$sandbox) {
_module_change_text_field_max_length('node', 'field_text', 280);
}
> NOTE: Codee snippet took from http://agaric.com/blogs/change-text-field-maximum-length-drupal-8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment