You are here

class HubspotWebformHandler in HubSpot 3.x

Same name and namespace in other branches
  1. 8 src/Plugin/WebformHandler/HubspotWebformHandler.php \Drupal\hubspot\Plugin\WebformHandler\HubspotWebformHandler

Webform submission remote post handler.

Plugin annotation


@WebformHandler(
  id = "hubspot_webform_handler",
  label = @Translation("HubSpot Webform Handler"),
  category = @Translation("External"),
  description = @Translation("Sends a webform submission to a Hubspot form."),
  cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
  results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
)

Hierarchy

Expanded class hierarchy of HubspotWebformHandler

1 file declares its use of HubspotWebformHandler
hubspot.install in ./hubspot.install
Installation file for hubspot.

File

src/Plugin/WebformHandler/HubspotWebformHandler.php, line 30

Namespace

Drupal\hubspot\Plugin\WebformHandler
View source
class HubspotWebformHandler extends WebformHandlerBase {

  /**
   * The node storage.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The mail manager.
   *
   * @var \Drupal\Core\Mail\MailManagerInterface
   */
  protected $mailManager;

  /**
   * Internal reference to the hubspot forms.
   *
   * @var \Drupal\hubspot\Hubspot
   */
  protected $hubspot;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $instance->entityTypeManager = $container
      ->get('entity_type.manager');
    $instance->mailManager = $container
      ->get('plugin.manager.mail');
    $instance->hubspot = $container
      ->get('hubspot.hubspot');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function getSummary() : array {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) : array {

    // First check if hubspot is connected.
    if (!$this->hubspot
      ->isConfigured()) {
      $form['mapping']['notice'] = [
        '#type' => 'item',
        '#title' => $this
          ->t('Notice'),
        '#markup' => $this
          ->t('Your site account is not connected to a Hubspot account, please @admin_link first.', [
          '@admin_link' => Link::createFromRoute('connect to Hubspot', 'hubspot.admin_settings'),
        ]),
      ];
      return $form;
    }
    $settings = $this
      ->getSettings();
    $default_hubspot_guid = $settings['form_guid'] ?? NULL;
    $this->webform = $this
      ->getWebform();
    $form['mapping'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Field Mapping'),
    ];
    try {
      $hubspot_forms = $this->hubspot
        ->getHubspotForms();
    } catch (HubspotException $e) {
      $this
        ->messenger()
        ->addWarning('Unable to load hubspot form info.');
      return $form;
    }
    $hubspot_forms = array_column($hubspot_forms, NULL, 'guid');
    $options = array_column($hubspot_forms, 'name', 'guid');

    // Sort $options alphabetically and retain key (guid).
    asort($options, SORT_STRING | SORT_FLAG_CASE);

    // Select list of forms on hubspot.
    $form['mapping']['hubspot_form'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Choose a hubspot form:'),
      '#options' => $options,
      '#default_value' => $default_hubspot_guid,
      '#empty_option' => $this
        ->t('Select a form'),
      '#ajax' => [
        'callback' => [
          $this,
          'showWebformFields',
        ],
        'event' => 'change',
        'wrapper' => 'edit-settings-mapping-field-group-fields-wrapper',
      ],
    ];

    // Fieldset to contain mapping fields.
    $form['mapping']['field_group'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Fields to map for form: @label', [
        '@label' => $this->webform
          ->label(),
      ]),
      '#states' => [
        'invisible' => [
          ':input[name="settings[mapping][hubspot_form]"]' => [
            'value' => '--donotmap--',
          ],
        ],
      ],
    ];
    $form['mapping']['field_group']['fields'] = [
      '#type' => 'container',
      '#prefix' => '<div id="edit-settings-mapping-field-group-fields-wrapper">',
      '#suffix' => '</div>',
      '#markup' => '',
    ];
    $form_values = $form_state
      ->getValues();

    // Generally, these elements cannot be submitted to HubSpot.
    $exclude_elements = [
      'webform_actions',
      'webform_flexbox',
      'webform_markup',
      'webform_more',
      'webform_section',
      'webform_wizard_page',
      'webform_message',
      'webform_horizontal_rule',
      'webform_terms_of_service',
      'webform_computed_token',
      'webform_computed_twig',
      'webform_element',
      'processed_text',
      'captcha',
      'container',
      'details',
      'fieldset',
      'item',
      'label',
    ];
    $consent_field_types = [
      'checkbox',
      'checkboxes',
      'webform_terms_of_service',
      'radios',
      'select',
    ];
    $components = $this->webform
      ->getElementsInitializedAndFlattened();
    $webform_fields_options = [
      '--donotmap--' => 'Do Not Map',
    ];
    $webform_consent_fields_options = [];
    foreach ($components as $webform_field => $value) {
      if (!in_array($value['#type'], $exclude_elements)) {
        $key = $webform_field;
        $title = (@$value['#title'] ?: $webform_field) . ' (' . $value['#type'] . ')';
        if ($value['#webform_composite']) {

          // Loop through a composite field to get all fields.
          foreach ($value['#webform_composite_elements'] as $composite_field => $composite_value) {
            $key = $webform_field . ':' . $composite_field;
            $webform_fields_options[$key] = (@$value['#title'] . ': ' . $composite_value['#title'] ?: $key) . ' (' . $composite_value['#type'] . ')';
          }
        }
        else {
          $webform_fields_options[$webform_field] = (@$value['#title'] ?: $webform_field) . ' (' . $value['#type'] . ')';
          if (in_array($value['#type'], $consent_field_types)) {
            $webform_consent_fields_options[$webform_field] = (@$value['#title'] ?: $webform_field) . ' (' . $value['#type'] . ')';
          }
        }
      }
    }
    if (empty($webform_consent_fields_options)) {
      $webform_consent_fields_options['none'] = $this
        ->t('No consent fields available.');
    }

    // Apply default values if available.
    if (!empty($form_values['mapping']['hubspot_form']) || !empty($default_hubspot_guid)) {
      if (!empty($form_values['mapping']['hubspot_form'])) {
        $hubspot_guid = $form_values['mapping']['hubspot_form'];
      }
      else {
        $hubspot_guid = $default_hubspot_guid;
      }
      $hubspot_form = $hubspot_forms[$hubspot_guid] ?? NULL;
      if ($hubspot_form) {
        foreach ($hubspot_form->formFieldGroups as $fieldGroup) {
          foreach ($fieldGroup->fields as $field) {
            $form['mapping']['field_group']['fields'][$field->name] = [
              '#title' => $field->label . ' (' . $field->fieldType . ')',
              '#type' => 'select',
              '#options' => $webform_fields_options,
            ];
          }
          if (isset($settings['field_mapping'][$field->name])) {
            $form['mapping']['field_group']['fields'][$field->name]['#default_value'] = $settings['field_mapping'][$field->name];
          }
        }
      }
    }
    $form['legal_consent'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Legal Consent'),
      'include' => [
        '#type' => 'select',
        '#title' => $this
          ->t('Include Legal Consent status'),
        '#options' => [
          'never' => $this
            ->t('Never'),
          'always' => $this
            ->t('Always'),
          'conditionally' => $this
            ->t('Conditionally'),
        ],
        '#parents' => [
          'settings',
          'legal_consent',
          'include',
        ],
      ],
      'source' => [
        '#type' => 'container',
        '#prefix' => '<div id="edit-settings-legal-consent-source-wrapper">',
        '#suffix' => '</div>',
        'element' => [
          '#type' => 'select',
          '#title' => 'Source Element',
          '#states' => [
            'visible' => [
              '#edit-settings-legal-consent-include' => [
                'value' => 'conditionally',
              ],
            ],
          ],
          '#parents' => [
            'settings',
            'legal_consent',
            'source',
            'element',
          ],
          '#empty_option' => $this
            ->t('Select'),
          '#options' => $webform_consent_fields_options,
          '#ajax' => [
            'callback' => [
              $this,
              'updateLegalConsentSource',
            ],
            'event' => 'change',
            'wrapper' => 'edit-settings-legal-consent-source-wrapper',
          ],
        ],
      ],
    ];
    if (!empty($form_values['legal_consent']['include']) && !empty($form_values['legal_consent']['source']['element']) && isset($components[$form_values['legal_consent']['source']['element']]) && isset($components[$form_values['legal_consent']['source']['element']]['#options'])) {
      $form['legal_consent']['source']['option'] = [
        '#type' => 'select',
        '#title' => 'Source Value',
        '#states' => [
          'visible' => [
            '#edit-settings-legal-consent-include' => [
              'value' => 'conditionally',
            ],
          ],
        ],
        '#parents' => [
          'settings',
          'legal_consent',
          'source',
          'option',
        ],
        '#options' => $components[$form_values['legal_consent']['source']['element']]['#options'],
      ];
    }
    $form['subscriptions'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Subscriptions'),
    ];
    try {
      $available_subscriptions = $this->hubspot
        ->hubspotGetSubscriptions();
      $subscription_options = [];
      foreach ($available_subscriptions as $subscription) {
        $subscription_options[$subscription->id] = $subscription->name;
      }
      $form_state
        ->addBuildInfo('subscription_options', $subscription_options);
      $form_state
        ->addBuildInfo('webform_consent_fields_options', $webform_consent_fields_options);
      if (empty($subscription_options)) {
        $form['subscriptions']['notice'] = [
          '#type' => 'item',
          '#markup' => $this
            ->t('No subscriptions available.'),
        ];
      }
      else {
        $form['subscriptions']['mapping'] = [
          '#type' => 'table',
          '#prefix' => '<div id="edit-settings-subscriptions-mapping-wrapper">',
          '#suffix' => '</div>',
          '#header' => [
            $this
              ->t('Subscription'),
            $this
              ->t('Mapping'),
            $this
              ->t('Actions'),
          ],
          '#empty' => $this
            ->t('No configured subscriptions'),
        ];
        $subscriptions = $form_values['subscriptions']['mapping'] ?? $settings['subscriptions'] ?? [];
        if ($subscriptions === '') {
          $subscriptions = [];
        }
        $form['subscriptions']['add'] = [
          '#type' => 'button',
          '#value' => $this
            ->t('Add Subscription'),
          '#ajax' => [
            'callback' => [
              $this,
              'addSubscription',
            ],
            'event' => 'click',
            'wrapper' => 'edit-settings-subscriptions-mapping-wrapper',
          ],
          '#parents' => [
            'settings',
            'subscriptions',
            'add',
          ],
        ];
        if ($form_state
          ->getTriggeringElement() && $form_state
          ->getTriggeringElement()['#parents'] == $form['subscriptions']['add']['#parents']) {
          $subscriptions[] = [];
        }
        foreach ($subscriptions as $key => $subscription) {
          $form['subscriptions']['mapping'][$key] = $this
            ->buildSubscriptionRow($key, $subscription_options, $webform_consent_fields_options, $subscription);
        }
      }
    } catch (BadRequest $e) {
      $form['subscriptions']['notice'] = [
        '#type' => 'item',
        '#markup' => $this
          ->t('Unable to load Email Subscription Types. Please re-authorize the integration.'),
      ];
    }
    return $form;
  }

  /**
   * Build row for the subscription table.
   *
   * @param mixed $index
   *   THe row id.
   * @param array $subscription_options
   *   The subscription options.
   * @param array $default_values
   *   The configured values.
   *
   * @return array
   *   Render array for the row.
   */
  protected function buildSubscriptionRow($index, array $subscription_options, array $webform_consent_fields_options, array $default_values = []) : array {
    $row = [
      '#attributes' => [
        'id' => 'edit-settings-subscriptions-mapping-' . $index,
      ],
      'subscription' => [
        '#type' => 'select',
        '#title' => $this
          ->t('Subscription Name'),
        '#title_display' => 'invisible',
        '#empty_option' => $this
          ->t('Select'),
        '#required' => TRUE,
        '#options' => $subscription_options,
        '#parents' => [
          'settings',
          'subscriptions',
          'mapping',
          $index,
          'subscription',
        ],
      ],
      'mapping' => [
        '#type' => 'container',
        '#prefix' => '<div id="edit-settings-subscriptions-mapping-' . $index . '-mapping-wrapper">',
        '#suffix' => '</div>',
        'include' => [
          '#type' => 'select',
          '#title' => 'Include',
          '#options' => [
            'always' => $this
              ->t('Always'),
            'conditionally' => $this
              ->t('Conditionally'),
          ],
          '#ajax' => [
            'callback' => [
              $this,
              'updateSubscriptionSource',
            ],
            'event' => 'change',
            'wrapper' => 'edit-settings-subscriptions-mapping-' . $index . '-mapping-wrapper',
          ],
          '#required' => TRUE,
          '#parents' => [
            'settings',
            'subscriptions',
            'mapping',
            $index,
            'mapping',
            'include',
          ],
        ],
      ],
      'remove' => [
        '#type' => 'button',
        '#value' => $this
          ->t('Remove'),
        '#ajax' => [
          'callback' => [
            $this,
            'removeSubscription',
          ],
          'event' => 'click',
          'wrapper' => 'edit-settings-legal-consent-source-wrapper',
        ],
        '#parents' => [
          'settings',
          'subscriptions',
          'mapping',
          $index,
          'remove',
        ],
      ],
    ];
    $components = $this->webform
      ->getElementsInitializedAndFlattened();
    if ($default_values['mapping']['include'] == 'conditionally') {
      $row['mapping']['element'] = [
        '#type' => 'select',
        '#title' => $this
          ->t('Element'),
        '#states' => [
          'visible' => [
            '#edit-settings-subscriptions-mapping-' . $index . '-mapping-include' => [
              'value' => 'conditionally',
            ],
          ],
        ],
        '#required' => TRUE,
        '#empty_option' => $this
          ->t('Select'),
        '#options' => $webform_consent_fields_options,
        '#ajax' => [
          'callback' => [
            $this,
            'updateSubscriptionSource',
          ],
          'event' => 'change',
          'wrapper' => 'edit-settings-subscriptions-mapping-' . $index . '-mapping-wrapper',
        ],
        '#parents' => [
          'settings',
          'subscriptions',
          'mapping',
          $index,
          'mapping',
          'element',
        ],
      ];
      if (!empty($default_values['mapping']['element']) && isset($components[$default_values['mapping']['element']]) && isset($components[$default_values['mapping']['element']]['#options'])) {
        $row['mapping']['value'] = [
          '#type' => 'select',
          '#title' => $this
            ->t('Value'),
          '#required' => TRUE,
          '#states' => [
            'visible' => [
              '#edit-settings-subscriptions-mapping-' . $index . '-include' => [
                'value' => 'conditionally',
              ],
            ],
          ],
          '#options' => $components[$default_values['mapping']['element']]['#options'],
          '#parents' => [
            'settings',
            'subscriptions',
            'mapping',
            $index,
            'mapping',
            'option',
          ],
        ];
      }
    }
    return $row;
  }

  /**
   * AJAX callback for hubspot form change event.
   *
   * @param array $form
   *   Active form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Active form state.
   *
   * @return array
   *   Render array.
   */
  public function showWebformFields(array $form, FormStateInterface $form_state) : array {
    return $form['settings']['mapping']['field_group']['fields'];
  }

  /**
   * AJAX callback for hubspot form change event.
   *
   * @param array $form
   *   Active form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Active form state.
   *
   * @return array
   *   Render array.
   */
  public function updateLegalConsentSource(array $form, FormStateInterface $form_state) : array {
    return $form['settings']['legal_consent']['source'];
  }

  /**
   * AJAX callback for hubspot form change event.
   *
   * @param array $form
   *   Active form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Active form state.
   *
   * @return array
   *   Render array.
   */
  public function addSubscription(array $form, FormStateInterface $form_state) : array {
    return $form['settings']['subscriptions']['mapping'];
  }

  /**
   * Ajax call back for removing subscription mapping row.
   *
   * @param array $form
   *   Drupal form render array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Drupal form state for ajax callback.
   *
   * @return mixed
   *   Drupal ajax response.
   */
  public function removeSubscription(array &$form, FormStateInterface $form_state) {
    $trigger = $form_state
      ->getTriggeringElement();
    $element_path = $trigger['#parents'];
    array_pop($element_path);
    $selector = '#edit-' . implode('-', $element_path);
    $response = new AjaxResponse();
    $response
      ->addCommand(new RemoveCommand($selector));
    return $response;
  }

  /**
   * Ajax call back for removing subscription mapping row.
   *
   * @param array $form
   *   Drupal form render array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Drupal form state for ajax callback.
   *
   * @return mixed
   *   Drupal ajax response.
   */
  public function updateSubscriptionSource(array &$form, FormStateInterface $form_state) {
    $trigger = $form_state
      ->getTriggeringElement();
    $element_path = $trigger['#parents'];
    array_pop($element_path);
    $elem = NestedArray::getValue($form, $element_path);
    return $elem;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    if (!$this->hubspot
      ->isConfigured()) {
      return;
    }
    $form_values = $form_state
      ->getValues();
    $hubspot_id = $form_values['mapping']['hubspot_form'];
    $fields = $form_values['mapping']['field_group']['fields'];
    $settings = [];

    // Add new field mapping.
    if ($hubspot_id != '--donotmap--') {
      $settings['form_guid'] = $hubspot_id;
      $settings['field_mapping'] = array_filter($fields, function ($hubspot_field) {
        return $hubspot_field !== '--donotmap--';
      });
      $this
        ->messenger()
        ->addMessage($this
        ->t('Saved new field mapping.'));
    }
    $settings['legal_consent'] = $form_values['legal_consent'];
    if ($settings['legal_consent']['include'] != 'conditionally') {
      unset($settings['legal_consent']['source']);
    }
    $settings['subscriptions'] = $form_values['subscriptions']['mapping'];
    $this
      ->setSettings($settings);
  }

  /**
   * {@inheritdoc}
   */
  public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
    $operation = $update ? 'update' : 'insert';
    $this
      ->remotePost($operation, $webform_submission);
  }

  /**
   * Get hubspot settings.
   *
   * @return array
   *   An associative array containing hubspot configuration values.
   */
  public function getSettings() : array {
    $configuration = $this
      ->getConfiguration();
    return $configuration['settings'] ?? [];
  }

  /**
   * Set hubspot settings.
   *
   * @param array $settings
   *   An associative array containing hubspot configuration values.
   */
  public function setSettings(array $settings) {
    $configuration = $this
      ->getConfiguration();
    $configuration['settings'] = $settings;
    $this
      ->setConfiguration($configuration);
  }

  /**
   * Execute a remote post.
   *
   * @param string $operation
   *   The type of webform submission operation to be posted. Can be 'insert',
   *   'update', or 'delete'.
   * @param \Drupal\webform\WebformSubmissionInterface $webform_submission
   *   The webform submission to be posted.
   */
  protected function remotePost($operation, WebformSubmissionInterface $webform_submission) {

    // Get the hubspot config settings.
    $request_post_data = $this
      ->getPostData($operation, $webform_submission);
    $entity_type = $request_post_data['entity_type'];
    $context = [];

    // Get webform.
    $webform = $this
      ->getWebform();

    // Get all components.
    $elements = $webform
      ->getElementsDecodedAndFlattened();

    // Loop through components and set new value for checkbox fields.
    foreach ($elements as $component_key => $component) {
      if ($component['#type'] == 'checkbox') {
        $webform_submission
          ->setElementData($component_key, $webform_submission
          ->getElementData($component_key) ? 'true' : 'false');
      }
    }
    if ($entity_type) {
      $entity_storage = $this->entityTypeManager
        ->getStorage($entity_type);
      $entity = $entity_storage
        ->load($request_post_data['entity_id']);
      $form_title = $entity
        ->label();
      $page_url = Url::fromUserInput($request_post_data['uri'], [
        'absolute' => TRUE,
      ])
        ->toString();
    }
    else {

      // Case 2: Webform it self.
      // Webform title.
      $form_title = $this
        ->getWebform()
        ->label();
      $page_url = $this->webform
        ->toUrl('canonical', [
        'absolute' => TRUE,
      ])
        ->toString();
    }
    $context['pageUri'] = $page_url;
    $settings = $this
      ->getSettings();
    $form_guid = $settings['form_guid'];
    $field_mapping = $settings['field_mapping'];
    $webform_values = $webform_submission
      ->getData();
    $form_values = [];
    foreach ($field_mapping as $hubspot_field => $webform_path) {
      if ($webform_path != '--donotmap--') {
        if (strpos($webform_path, ':') !== FALSE) {

          // Is composite element.
          $composite = explode(':', $webform_path);
          $composite_value = NestedArray::getValue($webform_values, $composite);
          $form_values[$hubspot_field] = $composite_value;
        }
        else {

          // Not a composite element.
          $form_values[$hubspot_field] = $webform_values[$webform_path];
        }
      }
    }
    $request_body = [];
    if (isset($settings['legal_consent']) && $settings['legal_consent']['include'] != 'never') {
      if ($settings['legal_consent']['include'] == 'always' || in_array($elements[$settings['legal_consent']['source']['element']]['#type'], [
        'checkbox',
        'webform_terms_of_service',
      ]) && $webform_values[$settings['legal_consent']['source']['element']] == 1 || $webform_values[$settings['legal_consent']['source']['element']] == $settings['legal_consent']['source']['option']) {
        $request_body['legalConsentOptions']['consent']['consentToProcess'] = TRUE;
        $request_body['legalConsentOptions']['consent']['text'] = $settings['legal_consent']['include'] == 'always' ? $this
          ->t('I agree') : $elements[$settings['legal_consent']['source']['element']]['#title'];
      }
    }
    if (isset($settings['subscriptions'])) {
      foreach ($settings['subscriptions'] as $subscription) {
        if ($subscription['mapping']['include'] == 'always' || in_array($elements[$subscription['mapping']['element']]['#type'], [
          'checkbox',
          'webform_terms_of_service',
        ]) && $webform_values[$subscription['mapping']['element']] == 1 || $webform_values[$subscription['mapping']['element']] == $subscription['mapping']['option']) {
          $request_body['legalConsentOptions']['consent']['communications'][] = [
            'value' => TRUE,
            'subscriptionTypeId' => $subscription['subscription'],
            'text' => $subscription['mapping']['include'] == 'always' ? $this
              ->t('I agree') : $elements[$subscription['mapping']['element']]['#title'],
          ];
        }
      }
    }
    try {
      $response = $this->hubspot
        ->submitHubspotForm($form_guid, $form_values, $context, $request_body);

      // Debugging information.
      $config = $this->configFactory
        ->get('hubspot.settings');
      $hubspot_url = 'https://app.hubspot.com';
      $to = $config
        ->get('hubspot_debug_email');
      $default_language = \Drupal::languageManager()
        ->getDefaultLanguage()
        ->getId();
      $from = $config
        ->get('site_mail');
      if ($response) {
        $data = (string) $response
          ->getBody();
        if ($response
          ->getStatusCode() == '200' || $response
          ->getStatusCode() == '204') {
          $this->loggerFactory
            ->get('HubSpot')
            ->notice('Webform "@form" results successfully submitted to HubSpot.', [
            '@form' => $form_title,
          ]);
        }
        else {
          $this->loggerFactory
            ->get('HubSpot')
            ->notice('HTTP notice when submitting HubSpot data from Webform "@form". @code: <pre>@msg</pre>', [
            '@form' => $form_title,
            '@code' => $response
              ->getStatusCode(),
            '@msg' => $response
              ->getBody()
              ->getContents(),
          ]);
        }
        if ($config
          ->get('hubspot_debug_on')) {
          $this->mailManager
            ->mail('hubspot', 'hub_error', $to, $default_language, [
            'errormsg' => $data,
            'hubspot_url' => $hubspot_url,
            'node_title' => $form_title,
          ], $from);
        }
      }
      else {
        $this->loggerFactory
          ->get('HubSpot')
          ->notice('HTTP error when submitting HubSpot data from Webform "@form": <pre>@msg</pre>', [
          '@form' => $form_title,
          '@msg' => 'No response returned from Hubspot Client',
        ]);
      }
    } catch (HubspotException $e) {
      $this->loggerFactory
        ->get('HubSpot')
        ->notice('HTTP error when submitting HubSpot data from Webform "@form": <pre>@error</pre>', [
        '@form' => $form_title,
        '@error' => $e
          ->getResponse()
          ->getBody()
          ->getContents(),
      ]);
      watchdog_exception('HubSpot', $e);
    }
  }

  /**
   * Get a webform submission's post data.
   *
   * @param string $operation
   *   The type of webform submission operation to be posted. Can be 'insert',
   *   'update', or 'delete'.
   * @param \Drupal\webform\WebformSubmissionInterface $webform_submission
   *   The webform submission to be posted.
   *
   * @return array
   *   A webform submission converted to an associative array.
   */
  protected function getPostData($operation, WebformSubmissionInterface $webform_submission) {

    // Get submission and elements data.
    $data = $webform_submission
      ->toArray(TRUE);

    // Flatten data.
    // Prioritizing elements before the submissions fields.
    $data = $data['data'] + $data;
    unset($data['data']);
    return $data;
  }

}

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
HubspotWebformHandler::$entityTypeManager protected property The node storage. Overrides WebformEntityStorageTrait::$entityTypeManager
HubspotWebformHandler::$hubspot protected property Internal reference to the hubspot forms.
HubspotWebformHandler::$mailManager protected property The mail manager.
HubspotWebformHandler::addSubscription public function AJAX callback for hubspot form change event.
HubspotWebformHandler::buildConfigurationForm public function Form constructor. Overrides WebformHandlerBase::buildConfigurationForm
HubspotWebformHandler::buildSubscriptionRow protected function Build row for the subscription table.
HubspotWebformHandler::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
HubspotWebformHandler::getPostData protected function Get a webform submission's post data.
HubspotWebformHandler::getSettings public function Get hubspot settings. Overrides WebformPluginSettingsTrait::getSettings
HubspotWebformHandler::getSummary public function Returns a render array summarizing the configuration of the webform handler. Overrides WebformHandlerBase::getSummary
HubspotWebformHandler::postSave public function Acts on a saved webform submission before the insert or update hook is invoked. Overrides WebformHandlerBase::postSave
HubspotWebformHandler::remotePost protected function Execute a remote post.
HubspotWebformHandler::removeSubscription public function Ajax call back for removing subscription mapping row.
HubspotWebformHandler::setSettings public function Set hubspot settings. Overrides WebformPluginSettingsTrait::setSettings
HubspotWebformHandler::showWebformFields public function AJAX callback for hubspot form change event.
HubspotWebformHandler::submitConfigurationForm public function Form submission handler. Overrides WebformHandlerBase::submitConfigurationForm
HubspotWebformHandler::updateLegalConsentSource public function AJAX callback for hubspot form change event.
HubspotWebformHandler::updateSubscriptionSource public function Ajax call back for removing subscription mapping row.
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.
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::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableInterface::defaultConfiguration 9
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::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::setSetting public function