/**
* Helper function to change the max length of a text field.
*/
function MYMODULE_change_text_field_max_length($field_name, $new_length) {
$field_table = 'field_data_' . $field_name;
$field_revision_table = 'field_revision_' . $field_name;
$field_column = $field_name . '_value';
// Alter value field length in fields table.
db_query("UPDATE `{$field_table}` SET `{$field_column}`=SUBSTR(`{$field_column}`, 0, {$new_length})");
db_query("ALTER TABLE `{$field_table}` CHANGE `{$field_column}` `{$field_column}` VARCHAR( {$new_length} )");
// Alter value field length in fields revision table.
db_query("UPDATE `{$field_revision_table}` SET `{$field_column}`=SUBSTR(`{$field_column}`, 0, {$new_length})");
db_query("ALTER TABLE `{$field_revision_table}` CHANGE `{$field_column}` `{$field_column}` VARCHAR( {$new_length} )");
// Update field config with new max length.
$result = db_query("SELECT CAST(`data` AS CHAR(10000) CHARACTER SET utf8) FROM `field_config` WHERE field_name = '{$field_name}'");
$config = $result->fetchField();
$config_array = unserialize($config);
$config_array['settings']['max_length'] = $new_length;
$config = serialize($config_array);
db_update('field_config')
->fields(array('data' => $config))
->condition('field_name', $field_name)
->execute();
}
/**
* Change max_length of Name field
*/
function mymodule_update_7002() {
MYMODULE_change_text_field_max_length('field_name', 50);
}
Source:
http://nathan.rambeck.org/blog/42-modify-drupal-7-text-field-maximum-length
Drupal 8
Here is the version of the same function proposed by @Christopher:
/**
* Utility to change the max length of a text field.
*
* @param string $field_name
* Field name.
* @param int $new_length
* Field length in characters.
*
* @throws \DrupalUpdateException
*/
function MYMODULE_change_text_field_max_length($field_name, $new_length) {
// The transaction opens here.
$txn = db_transaction();
try {
// Update field content tables with new max length.
foreach (['field_data_', 'field_revision_'] as $prefix) {
db_query('
ALTER TABLE {' . $prefix . $field_name . '}
MODIFY ' . $field_name . '_value VARCHAR( ' . $new_length . ' )
');
}
// Update field config record with new max length.
$result = db_query("
SELECT CAST(data AS CHAR(10000) CHARACTER SET utf8)
FROM {field_config}
WHERE field_name = :field_name
", [':field_name' => $field_name]
);
$config = $result->fetchField();
if ($config) {
$config_array = unserialize($config);
$config_array['settings']['max_length'] = $new_length;
$new_config = serialize($config_array);
db_update('field_config')
->fields(['data' => $new_config])
->condition('field_name', $field_name)
->execute();
}
}
catch (Exception $e) {
// Something went wrong somewhere, so roll back now.
$txn->rollback();
// Allow update to be re-run when errors are fixed.
throw new \DrupalUpdateException(
"Failed to change $field_name field max length: " . $e->getMessage(),
$e->getCode(), $e
);
}
}