2
4

【Drupal】フィールドの値を空にしたい。

Last updated at Posted at 2023-12-02

以前、新機能のリリースに合わせて、デプロイ時に特定のフィールドの値を空にするという実装を行いました。
そこで、中々空にすることができずハマった経験があったので、備忘録として残します。

やりたいこと

一度、やりたいことを整理します。
「記事コンテンツタイプのfugaフィールドの値を空にしたい」です。

実装

失敗例

まずは、失敗例から...

function hoge() {
  foreach (\Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
    'type' => 'article',
  ]) as $node) {
    $node->get('field_fuga')->delete();
  }
}

正解

function hoge() {
  foreach (\Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
      'type' => 'article',
  ]) as $node) {
    $node->set('field_fuga', NULL)->save();
  }
}

Coreソース内のdelete();メソッドを追って関数内を見てみましたが、値を空にするようなプログラムはかかれていないようです。
この場合は、set('{ フィールド名 }', NULL)なんですね。

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4