之前写了一个自定义实体,现在需要新增一个字段,但是我在新增之后去修改view时,发现在view的字段新增中找不到这个字段,我还以为需要重新创建view,但是在重新创建的view里仍然找不到这个字段。
后来请教了大佬才知道我添加字段的方法错了。因为这个实体已经有数据了,无法在实体定义的地方添加,只能用HOOK_update_N()实现,但是我使用的是 \Drupal::database()->schema()->addField() 的方法,所以数据表里字段添加成功了,但是实体需要的一些关联什么的都没有的。
正确的添加方法应该是这样:
function mymodule_update_9001() {
$field_storage_definition = BaseFieldDefinition::create('string')
->setLabel(t('Type'))
->setDescription(t('Content type'))
->setRequired(TRUE)
->setSetting('max_length', 255);
\Drupal::entityDefinitionUpdateManager()
->installFieldStorageDefinition('type', 'node', 'node', $field_storage_definition);
}
执行命令:drush updatedb,报错:
查了半天,把 setSetting(‘max_length’, 255);改成了 setSetting(‘max_length’, 20);
改了之后倒是没报错了,但是也没成功,数据库没变化,view也没变化。查了半天,原来是node写错了,\Drupal::entityDefinitionUpdateManager()
->installFieldStorageDefinition(‘type’, ‘node’, ‘node’, $field_storage_definition); 这里第二三个参数是node_type_id, 而node是entity type,所以这里应该是自定义实体的注解里面的id:
所以最终正确的应该是下面这个:
function mymodule_update_9001() {
$field_storage_definition = BaseFieldDefinition::create('string')
->setLabel(t('Type'))
->setDescription(t('Content type'))
->setRequired(TRUE)
->setSetting('max_length', 255);
\Drupal::entityDefinitionUpdateManager()
->installFieldStorageDefinition('type', 'custom_node_type_id', 'custom_node_type_id', $field_storage_definition);
}
PS:
新增的字段在custom entity那里也需要添加,这里只是更新数据库
参考:
https://drupal.stackexchange.com/questions/204435/add-new-field-to-custom-content-entity-type
https://www.drupal.org/node/3034742