You are here

function _pardot_form_submit in Pardot Integration 2.x

Pardot contact form submit.

Parameters

array $form: Form array.

\Drupal\Core\Form\FormStateInterface $form_state: Form state interface.

See also

pardot_form_contact_message_form_alter()

1 string reference to '_pardot_form_submit'
_set_pardot_form_submit in ./pardot.module
Set Pardot form submit.

File

./pardot.module, line 193
Contains pardot.module.

Code

function _pardot_form_submit(array &$form, FormStateInterface $form_state) {

  // Retrieve storage, where pardot_mapping was set in
  // pardot_form_contact_message_form_alter().
  $storage = $form_state
    ->getStorage();
  if (isset($storage['pardot_form_map'])) {

    /** @var \Drupal\contact\MessageForm $contact_message */
    $contact_message = $form_state
      ->getFormObject()
      ->getEntity();

    /** @var \Drupal\pardot\Service\PardotClient $pardot_api_client */
    $pardot_api_client = \Drupal::service('pardot.api_client');

    /** @var \Drupal\pardot\FormMap $pardot_form_map */
    $pardot_form_map = $storage['pardot_form_map'];
    $post_url = $pardot_form_map
      ->getPostUrl();
    $field_map_collection = $pardot_form_map
      ->getMappedFieldCollection();
    $visitor_email = '';
    $visitor_id = $pardot_api_client
      ->getVisitorId();
    $query_params = [];
    foreach ($field_map_collection as $field_map) {
      $plugin = $field_map
        ->getPlugin();
      if ($plugin && $plugin
        ->getFormattedValue($form_state)) {
        $value = $plugin
          ->getFormattedValue($form_state);
        $query_params[] = [
          $field_map
            ->getPardotKey() => $value,
        ];
        if ($field_map instanceof MappedEmailField) {
          $visitor_email = $value;
        }
      }
    }

    // Unable to use \Drupal\Component\Utility\UrlHelper::buildQuery() b/c
    // Pardot accepts multiple values using the same parameter key.
    $query_string = '';
    foreach ($query_params as $param) {
      $keys = array_keys($param);
      $key = reset($keys);
      $query_string .= rawurlencode($key) . '=' . str_replace('%2F', '/', rawurlencode($param[$key])) . '&';
    }
    $request_data = [
      'timeout' => 5,
      'query' => $query_string,
    ];
    $result = $pardot_api_client
      ->executePardotOperation($post_url, $request_data);

    // Connect the visitor ID to a prospect ID using the submitted email.
    if ($visitor_email && $visitor_id) {

      // Look up the prospect ID.
      $prospect_id = $pardot_api_client
        ->getPardotProspect($visitor_email);

      // Use the visitor ID to update the prospect.
      $prospect_is_assigned = $pardot_api_client
        ->assignPardotProspect($visitor_id, $prospect_id);
      if (!$prospect_is_assigned) {
        \Drupal::logger('pardot')
          ->error('Unable to assign Pardot prospect. Failure returned from API request.');
      }
    }
  }
}