以前、新機能のリリースに合わせて、デプロイ時に特定のフィールドの値を空にするという実装を行いました。
そこで、中々空にすることができずハマった経験があったので、備忘録として残します。
やりたいこと
一度、やりたいことを整理します。
「記事コンテンツタイプの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)
なんですね。