hook_update_N内のconfigから新しいフィールドを追加するにはどうすればよいですか?[複製]

Nov 23 2020

PHPコードで分類法を追加する必要があります。分類法には2つのフィールドが必要です。test_taxonomy.installに新しい関数を追加しましたが、機能しているようです。

function taxonomy_update_8805() {

    $config_path = 'modules/feature/test_taxonomy/config/update/'; $source = new FileStorage($config_path); \Drupal::entityManager()->getStorage('taxonomy_vocabulary') ->create($source->read('taxonomy.vocabulary.regulation'))
        ->save();
}

分類法に新しい語彙を追加しました。

ファイルの内容:

langcode: pl
status: true
dependencies:
  module:
    - test_remote_vocabulary
third_party_settings:
  test_remote_vocabulary:
    is_remote: 0
name: 'Test'
vid: regulation
description: 'Test desc'
hierarchy: 0
weight: 0
 

問題なのは、語彙にフィールドを追加しようとしたときです。2つのファイルを作成しました

field.storage.taxonomy_term.field_regulation_test.yml

langcode: pl
status: true
dependencies:
  module:
    - taxonomy
    - text
id: taxonomy_term.regulation.test
field_name: test_field
entity_type: taxonomy_term
type: text_long
settings: {  }
module: text
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

field.field.taxonomy_term.field_regulation_test.yml

langcode: pl
status: true
dependencies:
  config:
    - field.storage.taxonomy_term.field_regulation_test
    - taxonomy.vocabulary.regulation
id: taxonomy_term.regulation.test
field_name: test_content
entity_type: taxonomy_term
bundle: regulation
label: TEST
description: 'Tekst test'
required: true
translatable: false
default_value: {  }
default_value_callback: ''
settings: {  }
field_type: text_long

しかし、update_xxx関数でそれらをロードする方法がわかりません。

編集:私は試しました

    \Drupal::entityManager()->getStorage('taxonomy_term')
        ->create($source->read('field.storage.taxonomy_term.field_regulation_abo')) ->save(); \Drupal::entityManager()->getStorage('taxonomy_term') ->create($source->read('field.field.taxonomy_term.field_regulation_abo'))
        ->save();

しかし、モジュールを更新しようとしているときに、エンティティタイプtaxonomy_termのバンドルがありません

回答

3 leymannx Nov 23 2020 at 15:36

はい、依存する構成がインポートされる前にコンテンツを作成することはできません。これは古典的なDrupal8のパラドックスであり、最近新しいフックによって解決されましたhook_deploy_NAME(&$sandbox)。

最新のDrushに更新し、今後drush deployはデプロイメントルーチンの一部として実行しますdrush updb && drush cim。これにより、古いルーチンが置き換えられます。次に、モジュールに新しいファイルを作成しますMYMODULE.deploy.php。そこMYMODULE_deploy_NAME(&$sandbox)NAMEは、任意の一意の名前(または増分番号)を含めることができる実装があります。そして、このフックを使用hook_update_N(&$sandbox)して、質問のと同じように用語を作成します。

drush deploy 構成のインポートから依存する構成が作成された後、このフックが展開ルーチンの最後に取得されるようにします。