Score:0

How do I create a paragraph using a bundle class defined in another module?

cn flag

I have a controller in one module that generates paragraphs that are using unique bundle classes that I want to be able to use in other modules.

In my controller I have this

$bundle_class = \Drupal::service('class_resolver')->getInstanceFromDefinition('Drupal\other_module\Entity\Paragraph\StandardHero');
$paragraph = $bundle_class::create([
  'type' => 'standard_hero',
  'field_title' => [
    'value' => 'Test'
  ]
]);

It does recognize the class because if I change the class sting to gibberish it complains that that class is not found. But I get this error

ArgumentCountError: Too few arguments to function Drupal\Core\Entity\ContentEntityBase::__construct(), 0 passed in /core/lib/Drupal/Core/DependencyInjection/ClassResolver.php on line 31 and at least 2 expected in Drupal\Core\Entity\ContentEntityBase->__construct() (line 189 of core/lib/Drupal/Core/Entity/ContentEntityBase.php).

How can I create a paragraph of a specified bundle class that appears in a different module?

4uk4 avatar
cn flag
create() is a static method to create an instance, you don't need the class resolver to get an instance. BTW it is not important to identify the right class, the entity storage will do this automatically if the module providing the class is implementing the bundle class correctly.
Score:0
cn flag

4uk4 was correct. Defining the class was unnecessary. I was able to generate the paragraph with the proper bundle class applied automatically by just defining 'type' in the create method of the paragraphstorage class, like so

  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    // Injected.
    $this->entityTypeManager = $entity_type_manager;
    $this->paragraphStorage = $this->entityTypeManager->getStorage('paragraph');
    $this->paragraphViewBuilder = $this->entityTypeManager->getViewBuilder('paragraph');
  }

  public function show($type) {
    $query_params = \Drupal::request()->query->all();
    $paragraph_values = [
      'type' => $type
    ];

    $paragraph_values += $query_params;
    $paragraph = $this->paragraphStorage->create($paragraph_values);
    $build = $this->paragraphViewBuilder->view($paragraph);
    return $build;
  }
I sit in a Tesla and translated this thread with Ai:

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.