Search code examples
drupaldrupal-7

Drupal 7 does not save data correct after changing field type


I have a Drupal 7 application at a customer side. After changing a field in the DB from int to varchar(255) using the install file with following code (in *.install file):

$spec = array(
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE,
          'description' => t('The ID of the promotion, found in')
  );
  db_change_field('promotion', 'promotion_id', 'promotion_id', $spec);

The database is updated but when I save an entity with promotion_id like '8sf635' it will only save the 8 to the database. Also when I save the entity with 'qsfd7aer' it will save 0 in the database.

Can someone tells me how this can happen?

When checking the save code of the entity it looks like:

entity_save(self::ENTITY_NAME_PROPOSITION_PROMOTION, $promotion);

and in the $promotion object the promotion_id is still the full string.

It looks like the schema of the table is not updated. When running drupal_get_schema('dpp_bab_promotion', true) it shows the field as type int.


Solution

  • There are a couple of possible reasons. The first is that you didn't clear the cache so that the new schema can take effect. You said you cleared the cache, so the second, more likely is that you didn't add the change to the schema, but only did the database update. It sounds like the schema still thinks it's an int.

    Using hook_schema_alter is relatively easy. There are some good resources in the comments section of the API documentation: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_schema_alter/7.x