You are here

class TestEntityMappingWebformHandler in Webform 6.x

Same name and namespace in other branches
  1. 8.5 tests/modules/webform_test_handler/src/Plugin/WebformHandler/TestEntityMappingWebformHandler.php \Drupal\webform_test_handler\Plugin\WebformHandler\TestEntityMappingWebformHandler

Webform submission entity mapping test handler.

IMPORTANT: This handler is just a POC of mapping webform elements to entity fields using a Ajaxified configuration form.

Plugin annotation


@WebformHandler(
  id = "test_entity_mapping",
  label = @Translation("Test entity mapping"),
  category = @Translation("Testing"),
  description = @Translation("Tests mapping webform element's to entity fields."),
  cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
  results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_IGNORED,
  submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_OPTIONAL,
)

Hierarchy

Expanded class hierarchy of TestEntityMappingWebformHandler

File

tests/modules/webform_test_handler/src/Plugin/WebformHandler/TestEntityMappingWebformHandler.php, line 28

Namespace

Drupal\webform_test_handler\Plugin\WebformHandler
View source
class TestEntityMappingWebformHandler extends WebformHandlerBase {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The entity field manager.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = new static($configuration, $plugin_id, $plugin_definition);
    $instance->entityTypeManager = $container
      ->get('entity_type.manager');
    $instance->entityFieldManager = $container
      ->get('entity_field.manager');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'entity_type' => 'node',
      'bundle' => 'page',
      'fields' => [],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getSummary() {
    return [
      '#markup' => Yaml::encode($this->configuration),
      '#prefix' => '<pre>',
      '#suffix' => '<pre>',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $this
      ->applyFormStateToConfiguration($form_state);

    // Define #ajax callback.
    $ajax = [
      'callback' => [
        get_class($this),
        'ajaxCallback',
      ],
      'wrapper' => 'webform-test-ajax-container',
    ];

    /**************************************************************************/

    // Entity type.

    /**************************************************************************/

    // Get entity type options.
    $entity_type_options = [];
    foreach ($this->entityTypeManager
      ->getDefinitions() as $entity_type_id => $entity_type) {
      if ($entity_type instanceof ContentEntityTypeInterface) {
        $entity_type_options[$entity_type_id] = $entity_type
          ->getLabel();
      }
    }
    $form['entity_type_container'] = [
      '#type' => 'container',
    ];
    $form['entity_type_container']['entity_type'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Entity type'),
      '#default_value' => $this->configuration['entity_type'],
      '#options' => $entity_type_options,
      '#required' => TRUE,
      '#ajax' => $ajax,
    ];

    /**************************************************************************/

    // Bundles.

    /**************************************************************************/

    // Get entity type bundle options.

    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity_type */
    $entity_type = $this->entityTypeManager
      ->getDefinition($this->configuration['entity_type']);
    $bundle_options = [];
    if ($bundle_entity_type = $entity_type
      ->getBundleEntityType()) {
      if ($bundles = $this->entityTypeManager
        ->getStorage($bundle_entity_type)
        ->loadMultiple()) {
        foreach ($bundles as $bundle_id => $bundle) {
          $bundle_options[$bundle_id] = $bundle
            ->label();
        }
      }
    }
    if (empty($bundle_options)) {
      $bundle_options[$this->configuration['entity_type']] = $this->configuration['entity_type'];
      $access = FALSE;
    }
    else {
      $access = TRUE;
    }
    $form['bundle_container'] = [
      '#type' => 'container',
      '#attributes' => [
        'id' => 'webform-test-ajax-container',
      ],
    ];
    $this->configuration['bundle'] = isset($bundle_options[$this->configuration['bundle']]) ? $this->configuration['bundle'] : reset(array_keys($bundle_options));
    $form['bundle_container']['bundle'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Bundles'),
      '#default_value' => $this->configuration['bundle'],
      '#options' => $bundle_options,
      '#ajax' => $ajax,
      '#access' => $access,
    ];

    /**************************************************************************/

    // Fields.

    /**************************************************************************/

    // Get elements options.
    $element_options = [];
    $elements = $this->webform
      ->getElementsInitializedFlattenedAndHasValue();
    foreach ($elements as $element_key => $element) {
      $element_options[$element_key] = isset($element['#title']) ? $element['#title'] : $element_key;
    }

    // Get field options.
    $fields = $this->entityFieldManager
      ->getFieldDefinitions($this->configuration['entity_type'], $this->configuration['bundle']);
    $field_options = [];
    foreach ($fields as $field_name => $field) {
      $field_options[$field_name] = $field
        ->getLabel();
    }
    $form['bundle_container']['fields'] = [
      '#type' => 'webform_mapping',
      '#title' => 'Fields',
      '#description' => $this
        ->t('Please select which fields webform submission data should be mapped to'),
      '#description_display' => 'before',
      '#default_value' => $this->configuration['fields'],
      '#required' => TRUE,
      '#source' => $element_options,
      '#destination' => $field_options,
    ];
    return $this
      ->setSettingsParents($form);
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);
    $this->configuration['entity_type'] = $form_state
      ->getValue('entity_type');
    $this->configuration['bundle'] = $form_state
      ->getValue('bundle');
    $this->configuration['fields'] = $form_state
      ->getValue('fields');
  }

  /**
   * Ajax callback.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   An associative array containing entity reference details element.
   */
  public function ajaxCallback(array $form, FormStateInterface $form_state) {
    return NestedArray::getValue($form, [
      'settings',
      'bundle_container',
    ]);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 2
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. 98
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TestEntityMappingWebformHandler::$entityFieldManager protected property The entity field manager.
TestEntityMappingWebformHandler::$entityTypeManager protected property The entity type manager. Overrides WebformEntityStorageTrait::$entityTypeManager
TestEntityMappingWebformHandler::ajaxCallback public function Ajax callback.
TestEntityMappingWebformHandler::buildConfigurationForm public function Form constructor. Overrides WebformHandlerBase::buildConfigurationForm
TestEntityMappingWebformHandler::create public static function IMPORTANT: Webform handlers are initialized and serialized when they are attached to a webform. Make sure not include any services as a dependency injection that directly connect to the database. This will prevent "LogicException: The database… Overrides WebformHandlerBase::create
TestEntityMappingWebformHandler::defaultConfiguration public function Gets default configuration for this plugin. Overrides WebformHandlerBase::defaultConfiguration
TestEntityMappingWebformHandler::getSummary public function Returns a render array summarizing the configuration of the webform handler. Overrides WebformHandlerBase::getSummary
TestEntityMappingWebformHandler::submitConfigurationForm public function Form submission handler. Overrides WebformHandlerBase::submitConfigurationForm
WebformEntityInjectionTrait::getWebform public function Get the webform that this handler is attached to.
WebformEntityInjectionTrait::getWebformSubmission public function Set webform and webform submission entity.
WebformEntityInjectionTrait::resetEntities public function Reset webform and webform submission entity.
WebformEntityInjectionTrait::setEntities public function
WebformEntityInjectionTrait::setWebform public function Set the webform that this is handler is attached to.
WebformEntityInjectionTrait::setWebformSubmission public function Get the webform submission that this handler is handling.
WebformEntityStorageTrait::$entityStorageToTypeMappings protected property An associate array of entity type storage aliases.
WebformEntityStorageTrait::getEntityStorage protected function Retrieves the entity storage.
WebformEntityStorageTrait::getSubmissionStorage protected function Retrieves the webform submission storage.
WebformEntityStorageTrait::getWebformStorage protected function Retrieves the webform storage.
WebformEntityStorageTrait::__get public function Implements the magic __get() method.
WebformHandlerBase::$conditions protected property The webform handler's conditions.
WebformHandlerBase::$conditionsResultCache protected property The webform handler's conditions result cache.
WebformHandlerBase::$conditionsValidator protected property The webform submission (server-side) conditions (#states) validator.
WebformHandlerBase::$configFactory protected property The configuration factory. 1
WebformHandlerBase::$handler_id protected property The webform handler ID.
WebformHandlerBase::$label protected property The webform handler label.
WebformHandlerBase::$loggerFactory protected property The logger factory.
WebformHandlerBase::$notes protected property The webform variant notes.
WebformHandlerBase::$renderer protected property The renderer. 1
WebformHandlerBase::$status protected property The webform handler status.
WebformHandlerBase::$tokenManager protected property The webform token manager. 6
WebformHandlerBase::$webform protected property The webform. Overrides WebformEntityInjectionTrait::$webform
WebformHandlerBase::$webformSubmission protected property The webform submission. Overrides WebformEntityInjectionTrait::$webformSubmission
WebformHandlerBase::$weight protected property The weight of the webform handler.
WebformHandlerBase::access public function Controls entity operation access to webform submission. Overrides WebformHandlerInterface::access 1
WebformHandlerBase::accessElement public function Controls entity operation access to webform submission element. Overrides WebformHandlerInterface::accessElement 1
WebformHandlerBase::alterElement public function Alter webform element. Overrides WebformHandlerInterface::alterElement 2
WebformHandlerBase::alterElements public function Alter webform submission webform elements. Overrides WebformHandlerInterface::alterElements 2
WebformHandlerBase::alterForm public function Alter webform submission form. Overrides WebformHandlerInterface::alterForm 3
WebformHandlerBase::applyFormStateToConfiguration protected function Apply submitted form state to configuration.
WebformHandlerBase::buildTokenTreeElement protected function Build token tree element. 2
WebformHandlerBase::cardinality public function Returns the webform handler cardinality settings. Overrides WebformHandlerInterface::cardinality
WebformHandlerBase::checkConditions public function Check handler conditions against a webform submission. Overrides WebformHandlerInterface::checkConditions
WebformHandlerBase::confirmForm public function Confirm webform submission form. Overrides WebformHandlerInterface::confirmForm 2
WebformHandlerBase::createElement public function Acts on a element after it has been created. Overrides WebformHandlerInterface::createElement 2
WebformHandlerBase::createHandler public function Acts on handler after it has been created and added to webform. Overrides WebformHandlerInterface::createHandler 2
WebformHandlerBase::deleteElement public function Acts on a element after it has been deleted. Overrides WebformHandlerInterface::deleteElement 2
WebformHandlerBase::deleteHandler public function Acts on handler after it has been removed. Overrides WebformHandlerInterface::deleteHandler 3
WebformHandlerBase::description public function Returns the webform handler description. Overrides WebformHandlerInterface::description
WebformHandlerBase::disable public function Disables the webform handler. Overrides WebformHandlerInterface::disable
WebformHandlerBase::elementTokenValidate protected function Validate form that should have tokens in it.
WebformHandlerBase::enable public function Enables the webform handler. Overrides WebformHandlerInterface::enable
WebformHandlerBase::getConditions public function Returns the conditions the webform handler. Overrides WebformHandlerInterface::getConditions
WebformHandlerBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
WebformHandlerBase::getHandlerId public function Returns the unique ID representing the webform handler. Overrides WebformHandlerInterface::getHandlerId
WebformHandlerBase::getLabel public function Returns the label of the webform handler. Overrides WebformHandlerInterface::getLabel
WebformHandlerBase::getLogger protected function Get webform or webform_submission logger.
WebformHandlerBase::getNotes public function Returns notes of the webform variant. Overrides WebformHandlerInterface::getNotes
WebformHandlerBase::getOffCanvasWidth public function Get configuration form's off-canvas width. Overrides WebformHandlerInterface::getOffCanvasWidth 1
WebformHandlerBase::getStatus public function Returns the status of the webform handler. Overrides WebformHandlerInterface::getStatus
WebformHandlerBase::getWeight public function Returns the weight of the webform handler. Overrides WebformHandlerInterface::getWeight
WebformHandlerBase::hasAnonymousSubmissionTracking public function Determine if the webform handler requires anonymous submission tracking. Overrides WebformHandlerInterface::hasAnonymousSubmissionTracking 1
WebformHandlerBase::isApplicable public function Determine if this handle is applicable to the webform. Overrides WebformHandlerInterface::isApplicable
WebformHandlerBase::isDisabled public function Returns the webform handler disabled indicator. Overrides WebformHandlerInterface::isDisabled
WebformHandlerBase::isEnabled public function Returns the webform handler enabled indicator. Overrides WebformHandlerInterface::isEnabled 1
WebformHandlerBase::isExcluded public function Checks if the handler is excluded via webform.settings. Overrides WebformHandlerInterface::isExcluded
WebformHandlerBase::isSubmissionOptional public function Returns the webform submission is optional indicator. Overrides WebformHandlerInterface::isSubmissionOptional
WebformHandlerBase::isSubmissionRequired public function Returns the webform submission is required indicator. Overrides WebformHandlerInterface::isSubmissionRequired
WebformHandlerBase::label public function Returns the webform handler label. Overrides WebformHandlerInterface::label
WebformHandlerBase::overrideSettings public function Alter/override a webform submission webform settings. Overrides WebformHandlerInterface::overrideSettings 3
WebformHandlerBase::postCreate public function Acts on a webform submission after it is created. Overrides WebformHandlerInterface::postCreate 2
WebformHandlerBase::postDelete public function Acts on deleted a webform submission before the delete hook is invoked. Overrides WebformHandlerInterface::postDelete 4
WebformHandlerBase::postLoad public function Acts on loaded webform submission. Overrides WebformHandlerInterface::postLoad 2
WebformHandlerBase::postPurge public function Acts on webform submissions after they are purged. Overrides WebformHandlerInterface::postPurge 1
WebformHandlerBase::postSave public function Acts on a saved webform submission before the insert or update hook is invoked. Overrides WebformHandlerInterface::postSave 5
WebformHandlerBase::preCreate public function Changes the values of an entity before it is created. Overrides WebformHandlerInterface::preCreate 2
WebformHandlerBase::preDelete public function Acts on a webform submission before they are deleted and before hooks are invoked. Overrides WebformHandlerInterface::preDelete 2
WebformHandlerBase::prepareForm public function Acts on an webform submission about to be shown on a webform submission form. Overrides WebformHandlerInterface::prepareForm
WebformHandlerBase::preprocessConfirmation public function Prepares variables for webform confirmation templates. Overrides WebformHandlerInterface::preprocessConfirmation 2
WebformHandlerBase::prePurge public function Acts on webform submissions before they are purged. Overrides WebformHandlerInterface::prePurge 1
WebformHandlerBase::preSave public function Acts on a webform submission before the presave hook is invoked. Overrides WebformHandlerInterface::preSave 2
WebformHandlerBase::replaceTokens protected function Replace tokens in text with no render context.
WebformHandlerBase::setConditions public function Sets the conditions for this webform handler. Overrides WebformHandlerInterface::setConditions
WebformHandlerBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
WebformHandlerBase::setHandlerId public function Sets the id for this webform handler. Overrides WebformHandlerInterface::setHandlerId
WebformHandlerBase::setLabel public function Sets the label for this webform handler. Overrides WebformHandlerInterface::setLabel
WebformHandlerBase::setNotes public function Set notes for this webform variant. Overrides WebformHandlerInterface::setNotes
WebformHandlerBase::setSettingsParents protected function Set configuration settings parents.
WebformHandlerBase::setSettingsParentsRecursively protected function Set configuration settings parents.
WebformHandlerBase::setStatus public function Sets the status for this webform handler. Overrides WebformHandlerInterface::setStatus
WebformHandlerBase::setWeight public function Sets the weight for this webform handler. Overrides WebformHandlerInterface::setWeight
WebformHandlerBase::submitForm public function Submit webform submission form. Overrides WebformHandlerInterface::submitForm 4
WebformHandlerBase::supportsConditions public function Determine if webform handler supports conditions. Overrides WebformHandlerInterface::supportsConditions
WebformHandlerBase::supportsTokens public function Determine if webform handler supports tokens. Overrides WebformHandlerInterface::supportsTokens
WebformHandlerBase::updateElement public function Acts on a element after it has been updated. Overrides WebformHandlerInterface::updateElement 2
WebformHandlerBase::updateHandler public function Acts on handler after it has been updated. Overrides WebformHandlerInterface::updateHandler 3
WebformHandlerBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm 3
WebformHandlerBase::validateForm public function Validate webform submission form. Overrides WebformHandlerInterface::validateForm 2
WebformHandlerInterface::CARDINALITY_SINGLE constant Value indicating a single plugin instances are permitted.
WebformHandlerInterface::CARDINALITY_UNLIMITED constant Value indicating unlimited plugin instances are permitted.
WebformHandlerInterface::RESULTS_IGNORED constant Value indicating webform submissions are not processed (i.e. email or saved) by the handler.
WebformHandlerInterface::RESULTS_PROCESSED constant Value indicating webform submissions are processed (i.e. email or saved) by the handler.
WebformHandlerInterface::SUBMISSION_OPTIONAL constant Value indicating webform submissions do not have to be stored in the database.
WebformHandlerInterface::SUBMISSION_REQUIRED constant Value indicating webform submissions must be stored in the database.
WebformPluginSettingsTrait::getSetting public function
WebformPluginSettingsTrait::getSettings public function
WebformPluginSettingsTrait::setSetting public function
WebformPluginSettingsTrait::setSettings public function