Skip to content

Instantly share code, notes, and snippets.

@heyrocker
Created April 18, 2013 18:05
Show Gist options
  • Save heyrocker/5414904 to your computer and use it in GitHub Desktop.
Save heyrocker/5414904 to your computer and use it in GitHub Desktop.
$field_name = 'field_article_type';
// Get the field info
$original_field = field_info_field($field_name);
$settings = $original_field['settings'];
$settings['allowed_values'] = array(
'articles' => 'Articles',
'news' => 'News',
'videos' => 'Videos',
);
// Create the data array that will be forced manually
$data['entity_types'] = $original_field['entity_types'];
$data['foreign keys'] = $original_field['foreign keys'];
$data['indexes'] = $original_field['indexes'];
$data['settings'] = $settings;
$data['translatable'] = $original_field['translatable'];
$data['storage'] = $original_field['storage'];
$data['id'] = $original_field['id'];
// We need to manually tamper with the DB since validations won't allow
// type & allowed_values changes for existing fields with field_update_field()
db_update('field_config')
->fields(array(
'type' => 'list_text',
'data' => serialize($data),
))
->condition('field_name', $field_name)
->execute();
// Change the schema so it holds text instead of ints
// For some reason db_change_field() won't accept 'text' type. Doing it manually.
db_query('ALTER TABLE {field_data_' . $field_name . '} CHANGE ' . $field_name . '_value ' . $field_name . '_value VARCHAR(255)');
// Update the data present in the field
$mappings = array(
1 => 'articles',
2 => 'news',
3 => 'videos',
);
foreach ($mappings as $mapping_index => $mapping_value) {
// Update the field with the new field key.
// Trying to load the nodes => updating field content => saving gives a MySQL error
// for mismatch of integer vs. text
db_update('field_data_' . $field_name)
->fields(array(
$field_name . '_value' => $mapping_value,
))
->condition($field_name . '_value', $mapping_index)
->execute();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment