Drupal – Veriye Sahip Bir Alanın Güncellenmesi (Hook Update)

Drupal 8.9.x sürümünde denenmiştir. modulname_update_8900 bir kez çalışacaktır. Sonraki kullanımda modulname_update_8901… (+1) olarak güncellemeniz gerekmektedir.

function modulename_update_8900() {

$database = \Drupal::database();

$entityType = 'node';
$fieldName = 'field_yourfield';
$table = $entityType . '__' . $fieldName;

$currentRows = NULL;
$newFieldsList = [];
$fieldStorage = FieldStorageConfig::loadByName($entityType, $fieldName);

if (is_null($fieldStorage)) {
	return;
}

// Get all current data from DB.
if ($database->schema()->tableExists($table)) {
  
	// The table data to restore after the update is completed.
    $currentRows = $database->select($table, 'n')
    ->fields('n')
    ->execute()
    ->fetchAll();
}

// Use existing field config for new field.
foreach ($fieldStorage->getBundles() as $bundle => $label) {
    $field = FieldConfig::loadByName($entityType, $bundle, $fieldName);
    $newField = $field->toArray();
    $newField['field_type'] = 'text_long';
    $newField['settings'] = [];
    $newFieldsList[] = $newField;
}

$newFieldStorage = $fieldStorage->toArray();
$newFieldStorage['type'] = 'text_long';
$newFieldStorage['settings'] = [];

// Deleting field storage which will also delete bundles(fields).
$fieldStorage->delete();

// Purge field data now to allow new field and field_storage with same name
// to be created.
field_purge_batch(40);

// Create new field storage.
$newFieldStorage = FieldStorageConfig::create($newFieldStorage);
$newFieldStorage->save();

// Create new fields.
foreach ($newFieldsList as $nfield) {
    $nfieldConfig = FieldConfig::create($nfield);
    $nfieldConfig->save();
}

// Restore existing data in new table.
if (!is_null($currentRows)) {
  foreach ($currentRows as $row) {
      $database->insert($table)
      ->fields((array) $row)
      ->execute();
  }
}
  
}