Score:0

Hook_install or hook_modules_installed save entity does not work

cn flag

I am trying to insert a new vocabulary to taxonomy because a custom entity from my custom module needs that vocabulary as an entity reference. I think it would be better to always insert the reference vocabulary to make it certain that it will always be there instead of doing it manually by the site.

The problem is the $entity->save() doesn't work neither in hook_install or in hook_modules_installed. I don't know what is the problem. My code is below:

\Drupal\my_module\my_module.install.php

$vocabulary = \Drupal::entityTypeManager()->getStorage('taxonomy_vocabulary')
    ->loadByProperties(['vid' => 'class']);

if (!empty($vocabulary)) {
    return;
}

$vocabulary = \Drupal::entityTypeManager()->getStorage('taxonomy_vocabulary')
    ->create([
        'vid' => 'class',
        'name' => 'Class',
        'description' => 'Product classes'
    ]);
$vocabulary->save();

The code is very similar in \Drupal\my_module\my_module.module. The diference is that I check if $module is the my_module first.

Does somebody have a clue about what is the problem?

leymannx avatar
ne flag
Is it maybe, that it works when you enable the module from the UI, but it doesn't work when you enable it from a configuration import?
ru flag
Remove the `.php` from your filename, it is only `my_module.install`
Jean da Silva avatar
cn flag
thanks for the help, but it didn't work either way. I've tried using the interface or with drush, and I've also tried to remove the .php, but it doesn't save the new vocabulary.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.