Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
WebformRenderElement.php 2.38 KiB
<?php

declare(strict_types=1);

namespace Drupal\graphql_webform\Plugin\GraphQL\DataProducer;

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\graphql\Plugin\GraphQL\DataProducer\DataProducerPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Renders a Webform element.
 *
 * @DataProducer(
 *   id = "webform_render_element",
 *   name = @Translation("Webform render element"),
 *   description = @Translation("Renders the Webform element."),
 *   produces = @ContextDefinition("any",
 *     label = @Translation("Rendered Webform element"),
 *   ),
 *   consumes = {
 *     "element" = @ContextDefinition("any",
 *       label = @Translation("Webform element as a render array"),
 *     )
 *   }
 * )
 */
class WebformRenderElement extends DataProducerPluginBase implements ContainerFactoryPluginInterface {

  /**
   * Constructs a new WebformRenderElement data producer.
   *
   * @param array $configuration
   *   The plugin configuration.
   * @param string $pluginId
   *   The plugin ID.
   * @param mixed $pluginDefinition
   *   The plugin definition.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer.
   */
  public function __construct(
    array $configuration,
    $pluginId,
    $pluginDefinition,
    protected RendererInterface $renderer,
  ) {
    parent::__construct($configuration, $pluginId, $pluginDefinition);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('renderer')
    );
  }

  /**
   * Renders the Webform element.
   *
   * @param array $element
   *   The Webform element as a render array.
   *
   * @return string
   *   The rendered Webform element.
   */
  public function resolve(array $element): string {
    // The Webform module is wrapping its elements in the 'form_element' theme
    // wrapper since it is designed to show its forms in the Drupal theming
    // layer. Remove the wrapper to render the element as a standalone element.
    if (!empty($element['#theme_wrappers'])) {
      $element['#theme_wrappers'] = array_diff($element['#theme_wrappers'], ['form_element']);
    }
    return (string) $this->renderer->renderPlain($element);
  }

}