首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将字段从string_long转换为text_long

将字段从string_long转换为text_long
EN

Drupal用户
提问于 2022-06-28 17:32:33
回答 1查看 209关注 0票数 0

我需要将段落上的字段从string_long类型转换为text_long类型。

字段中有数据,所以我不能在UI中更改它。

我将如何以编程方式做到这一点?

EN

回答 1

Drupal用户

发布于 2022-06-29 13:09:09

下面是我根据https://drupal.stackexchange.com/users/71454/miststudent2011提供的示例代码提出的解决方案。我不得不在这个特殊的情况下对它做一些调整:

代码语言:javascript
复制
/**
 * 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();
  }
}
票数 3
EN
页面原文内容由Drupal提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://drupal.stackexchange.com/questions/311827

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档