0

I have a custom module that defines a field wherein I erroneously set the 'not null' value to be FALSE when I should have set it to TRUE. Ideally I would like to remedy this by means of an update hook. How can I do that?

function MYMODULE_field_schema($field) {
  $columns = array(
    'payments' => array(
      'type' => 'varchar', 
      'length' => 20, 
      'not null' => FALSE,
      'description' => 'Number of payments made',
    ),
  );
  return array('columns' => $columns);
}

From reading the documentation it looks like I could do it by passing a field structure to field_update_field, but I don't know what to put in the field structure

function MYOTHERMODULE_update_70xx() {

 $field = array(
    // What should I put in here in order to change 'not null' to FALSE
    // and as a bonus, change the type from 'varchar' 
    // to an integer (number_integer?)
);

 field_update_field($field);
}

Am I over-simplifying things? I know it's often not possible to modify fields if they contain data, and in this particular case I can delete and re-create the content type without too much difficulty, but no point doing all of that if there's no need.

1

You need to ud db_change_field function to change structure of table field.

function MYOTHERMODULE_update_70xx() {
  db_change_field('tablename', 'payments', 'payments', array(
    'not null' => TRUE,
  ));
}
  • Thanks @vgoradiya, you pointed me in the right direction. I expanded a little on your answer in case it might help someone else in future. – Frank H. Mar 22 '16 at 0:54
0

For anyone who might stumble upon this in future, @vgoradiya pointed me in the right direction by mentioning the db_change_field function but what ultimately happens is the function creates a SQL 'ALTER TABLE' command, which has syntax like this:

ALTER TABLE table_name CHANGE field_name field_name  VARCHAR(20) NOT NULL DEFAULT '0'; 

So, in your call to db_change_field, you must provide the values that enable Drupal to build the SQL command. Also, if you have revisions enabled, you must apply the change to the revision table as well as the field table. This is what worked for me:

  $tables = array('field_data_field_stations',   
                  'field_revision_field_stations');
  $column = 'payments';
  $column_spec = array(
    'not null' => TRUE,
    'type' => 'varchar',
    'length' => '20',
    'default' => '0',
    );

  foreach ($tables as $table) {
    db_change_field($table, $column, $column, $column_spec);
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.