Skip to content

Instantly share code, notes, and snippets.

@ao5357
Created June 15, 2022 13:38
Show Gist options
  • Save ao5357/88d46037c222ad24c20872531af9f857 to your computer and use it in GitHub Desktop.
Save ao5357/88d46037c222ad24c20872531af9f857 to your computer and use it in GitHub Desktop.
A webform embed element for Acquia Site Studio, including dependency injection
<?php
namespace Drupal\webform_element\Plugin\CustomElement;
use Drupal\cohesion_elements\CustomElementPluginBase;
use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Webform element plugin for DX8.
*
* @package Drupal\cohesion\Plugin\CustomElement
*
* @CustomElement(
* id = "webform_element",
* label = @Translation("Webform element")
* )
*/
class WebformElement extends CustomElementPluginBase {
/**
* An instance of the entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected EntityTypeManagerInterface $entityTypeManager;
/**
* {@inheritdoc}
*/
public function __construct($configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entityTypeManager) {
$this->entityTypeManager = $entityTypeManager;
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager')
);
}
/**
* {@inheritdoc}
*/
public function getFields() {
return [
'webform' => [
'title' => 'Webform machine name',
'type' => 'textfield',
'required' => TRUE,
'validationMessage' => 'This field is required.',
],
];
}
/**
* {@inheritdoc}
*/
public function render($element_settings, $element_markup, $element_class, $element_context = []) {
try {
$webform = $this->entityTypeManager
->getStorage('webform')
->load($element_settings['webform']);
}
catch (InvalidPluginDefinitionException | PluginNotFoundException) {
}
$view_builder = $this->entityTypeManager
->getViewBuilder('webform');
$build = $view_builder->view($webform);
// Render the element.
return [
'#theme' => 'webform_element',
'#template' => 'webform-element-template',
'#elementSettings' => $element_settings,
'#elementMarkup' => $element_markup,
'#elementContext' => $element_context,
'#elementClass' => $element_class,
'#webform' => $build,
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment