Drupal 7 – Increase the size of a field that already has content

In one of our projects I have a text field in a content type that the size is of 20 chars, the product owner asked me to extend the size of this field since is very short. I went to manage fields and I found that if the field already has content the size can’t be changed with the UI.

As you can see, the control is disabled.

After asking for help to my mates, Marcos give me this link that explains how to do it manually. In a nutshell we just need to

  • Alter the size in the field_data_{{ field_name}} table.
  • Alter the size in the field_revision_{{ field_name}} table.
  • Alter the record in field_config table for the field_name, changing the max_length
  • If the field is managed by a feature, update the feature or change the size manually in the exported code.

How to do that, this code snippet is great to be added in a hook_updated.

function mymodule_update_7XXX() {
  $items = array();mymodule_field_maxlength_fix('field_name', 150); //150 is my required size
  return $items;
}

function mymodule_field_maxlength_fix($field_name, $maxlength = 255 {
  mymodule_alter_field_table($field_name, $maxlength);
  $data =mymodule_get_field_data($field_name);
  $data['settings']['max_length'] = (string) $maxlength;       
  mymodule_update_field_config($data, $field_name);
}

function mymodule_alter_field_table($field_name, $maxlength) {
  db_query("ALTER TABLE field_data_".$field_name." CHANGE ".$field_name."_value ".$field_name."_value VARCHAR( ".$maxlength." ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
  db_query("ALTER TABLE field_revision_".$field_name." CHANGE ".$field_name."_value ".$field_name."_value VARCHAR( ".$maxlength." ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
}

function mymodule_get_field_data($field_name) {
  $qry = "SELECT data FROM field_config WHERE field_name = :field_name";
  $result = db_query($qry, array(':field_name' => $field_name))->fetchObject();
  return unserialize($result->data);
}

function mymodule_update_field_config($data, $field_name) {
  $qry = "UPDATE field_config SET data = :data WHERE field_name = :field_name";
  db_query($qry, array(':data' => serialize($data), ':field_name' => $field_name)); 
}

After that, don’t forget update your feature that is traking this field if you have any.

Luis Tip: DO NOT FORGET TO MAKE A BACKUP Before run this update

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.