我需要将段落上的字段从string_long类型转换为text_long类型。
字段中有数据,所以我不能在UI中更改它。
我将如何以编程方式做到这一点?
发布于 2022-06-29 13:09:09
下面是我根据https://drupal.stackexchange.com/users/71454/miststudent2011提供的示例代码提出的解决方案。我不得不在这个特殊的情况下对它做一些调整:
/**
* Convert plain text field to formatted text field.
*/
function mymodule_update_9002() {
$entity_type = 'paragraph';
$field = 'field_paragraph_variant';
// Retrieve existing field data.
$database = \Drupal::database();
$tables = [
"{$entity_type}__$field",
"{$entity_type}_revision__$field",
];
$existing_data = [];
foreach ($tables as $table) {
// Get the old data.
$existing_data[$table] = $database->select($table)
->fields($table)
->execute()
->fetchAll(PDO::FETCH_ASSOC);
}
// Get the field config.
$field_storage = \Drupal::entityTypeManager()->getStorage('field_storage_config');
$field_storage_config = $field_storage->loadByProperties(['field_name' => $field]);
foreach ($field_storage_config as $field_storage) {
// Save the config as an array and change the type.
$new_field_storage = $field_storage->toArray();
$new_field_storage['type'] = 'text_long';
// Delete the original field, otherwise the new table columns won't get added.
$field_storage->delete();
// Re-create the field.
$new_field_storage = $field_storage->create($new_field_storage);
$new_field_storage->enforceIsNew(TRUE);
$new_field_storage->save();
}
// Restore the data.
foreach ($tables as $table) {
$insert_query = $database
->insert($table)
->fields([
'bundle',
'deleted',
'entity_id',
'revision_id',
'langcode',
'delta',
$field . '_value',
$field . '_format',
]);
foreach ($existing_data[$table] as $row) {
$row[$field . '_format'] = 'subscriber_text';
$insert_query->values(array_values($row));
}
$insert_query->execute();
}
}https://drupal.stackexchange.com/questions/311827
复制相似问题