Score:0

Iterate over bundles to create entity bundle class for each

in flag

I'm curious if anyone has a way to produce an entity bundle class for several bundles at once. For example:

function MYMODULE_entity_bundle_info_alter(&$bundles) {

  // My array of different content types.
  $target_bundles = ['page', 'article'];

  // Iterate over the content types.
  foreach($target_bundle as $bundle) {

    $Bundle = ucfirst($bundle); // page to Page
    $bundles['node'][$bundle]['class'] = $Bundle::class; // Page::class

  }
}

The problem I'm running into is the $Bundle::class part doesn't work. Is this possible?

Dylan avatar
kr flag
I think you have the class names wrong, I would debug the return for `EntityTypeBundleInfoInterface->getBundleInfo('node);`. and refer to 'ContentEntityStorageBase'
user106977 avatar
in flag
Thanks, Dylan. I edited my code sample because of some errors. The error I'm getting is: **Fatal error:** Cannot use ::class with dynamic class name. This got me pointed in the right direction. I didn't understand that `::class` simply returns the full namespace of the class. When I added that into my string concatenation for the $Bundle variable, everything worked. I'll post the working code in the answer. Thanks again!
Score:1
in flag

After some poking around, I realized the error I was getting:
Fatal error: Cannot use ::class with dynamic class name

Long story short, my problem was I didn't understand that ::class simply returns the full namespace of the class itself. Once I added in the full namespace to my $Bundle variable, everything worked nicely. The code below provides an efficient way to assign multiple entity bundles to their respective classes.

function mymodule_entity_bundle_info_alter(&$bundles) {

  // Array of content type machine names.
  $target_bundles = ['page', 'article'];

  // Iterate over the content types.
  foreach($target_bundle as $bundle) {

    // Turn 'page' to 'Page' and add the full namespace.
    $Bundle = 'Drupal\mymodule\Entity\' . ucfirst($bundle);

    $bundles['node'][$bundle]['class'] = $Bundle;
  }
} 
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.