Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to update a field storage length in hook_install (or hook_update). Note this does not cover more difficult things, like changing storage type altogether.
<?php
use Drupal\Core\Database\Database;
/**
* Implements hook_install().
*/
function mymodule_install() {
$connection = Database::getConnection('default');
// Modify tables directly. field.storage.paragraph.field_question
drupal_set_message('paragraph__field_question: altering database tables.', 'warning');
$connection->query(
'ALTER TABLE paragraph_revision__field_question MODIFY field_question_value varchar(512);'
);
$connection->query(
'ALTER TABLE paragraph__field_question MODIFY field_question_value varchar(512);'
);
// Force configuration to be set to match.
drupal_set_message('Checking config for any required updates.');
$config_factory = \Drupal::configFactory();
$config = $config_factory->getEditable('field.storage.paragraph.field_question');
if ($config->get('settings.max_length') != 512) {
drupal_set_message('Config needs updating; updating.', 'warning');
$config->set('settings.max_length', 512);
$config->save();
}
else {
drupal_set_message('Config has already been updated.');
}
// Live schemas.
drupal_set_message('Checking live schema matches database.');
$store = \Drupal::service("keyvalue")->get("entity.storage_schema.sql");
$data = $store->get("paragraph.field_schema_data.field_question");
$live_schema_change = FALSE;
foreach (["paragraph_revision__field_question", "paragraph__field_question"] as $table) {
if ($data[$table]["fields"]["field_question_value"]["length"] != 512) {
$data[$table]["fields"]["field_question_value"]["length"] = 512;
$live_schema_change = TRUE;
}
}
if ($live_schema_change) {
drupal_set_message('Live schema needs updating; updating.', 'warning');
$store->set("paragraph.field_schema_data.field_question", $data);
}
else {
drupal_set_message('Live schema has already been updated.');
}
// Last-installed schemas.
$schema_repository = \Drupal::service("entity.last_installed_schema.repository");
$last_max_length = $schema_repository->getLastInstalledFieldStorageDefinitions("paragraph");
$last_max_length = $last_max_length["field_question"]->getSetting("max_length");
if ($last_max_length != 512) {
drupal_set_message('Last installed schema record needs updating; updating.', 'warning');
$field_storage_definitions = \Drupal::entityManager()->getFieldStorageDefinitions("paragraph");
$field_storage_definitions["field_question"]->setSetting("max_length", 512);
// Now set as the most recent schema definition.
$schema_repository->setLastInstalledFieldStorageDefinitions(
"paragraph", $field_storage_definitions
);
}
else {
drupal_set_message('Last installed schema record has already been updated.');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment