0

I'm attempting to add a custom image field to my menu from a custom module like so

function my_module_entity_base_field_info(EntityTypeInterface $entity_type) {
  $fields = array();
      if ($entity_type->id() === 'menu_link_content') {
          $fields['menu_link_secondary_image'] = BaseFieldDefinition::create('image')
              ->setLabel(t('Menu link secondary image'))
              ->setDescription(t('Upload a secondary image related to this menu item'))
              ->setDisplayOptions('form',array('type' => 'image','weight' => 1))
              ->setDisplayConfigurable('form',TRUE)
          ->setSettings([
              'file_directory' => 'public://',
              'alt_field_required' => 'FALSE',
              'file_extensions' => 'png jpg jpeg',
          ]);

      return $fields;
    }
}

Then in my update function I have

function my_module_update_8001(){
    $entity_manager = \Drupal::entityManager();
    $definitions = $entity_manager->getLastInstallFieldStorageDefinitions('menu_link_content');
    if(!isset($definitions['menu_link_secondary_image']) || empty($definitions['menu_link_secondary_image'])){
        $definition = $entity_manager->getFieldStorageDefinitions('menu_link_content')['menu_link_secondary_image'];
        $entity_manager->onFieldStorageDefinitionCreate($definition);
    }
}

But when I attempt to run update.php it hangs and I get errors like

Notice: Undefined index: menu_link_secondary_image__alt in Drupal\Core\Entity\Sql\SqlContentEntityStorage->loadFromSharedTables()

Strangely enough I added a menu link afterwards and my field was actually there. I couldn't tell if my update actually worked and just didn't act as if it did, or if it already worked before hand and the update was unnecessary. Did I do something wrong?

UPDATE: I see that although my field appeared I'm unable to save it due to this error

Column not found: 1054 Unknown column 'menu_link_secondary_image__target_id' i

  • You need to install fields with \Drupal::entityDefinitionUpdateManager() ->installFieldStorageDefinition(), see node_update_8001() for example – Berdir Sep 19 '18 at 17:10
  • And you should duplicate the definition so that you can later do updates if necessary – Berdir Sep 19 '18 at 17:10
  • I'm not sure I know what you mean by duplicating the definition – Matt Sep 19 '18 at 17:19
1

Just update entities it will work: run the command drush entity-updates.
No need for hook_update_N.
You can add hook_install to update entities automatically when you install your module don't need to do it by command each time or get the error on every installation .


/**
 * Implements hook_install().
 */
function my_module_install() {
  \Drupal::service('entity.definition_update_manager')->applyUpdates();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.