0

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?

1
  • 1
    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.
    – 4uk4
    Dec 21, 2022 at 17:02

1 Answer 1

0

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;
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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