You are here

function pardot_contact_form_submit in Pardot Integration 8

Pardot contact form submit.

Parameters

array $form:

\Drupal\Core\Form\FormStateInterface $form_state:

See also

pardot_form_contact_message_form_alter()

1 string reference to 'pardot_contact_form_submit'
pardot_form_contact_message_form_alter in ./pardot.module
Implements hook_form_FORM_ID_alter().

File

./pardot.module, line 100
Pardot integration module.

Code

function pardot_contact_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_mapping'])) {
    $query_params = array();
    $mapped_fields = $storage['pardot_mapping']->mapped_fields;
    $values = $form_state
      ->getValues();
    foreach ($mapped_fields as $field_name => $pardot_key) {
      if (!empty($values[$field_name])) {
        $field_values = $form_state
          ->getValue($field_name);
        if (!is_array($field_values)) {
          $query_params[] = array(
            $pardot_key => $field_values,
          );
        }
        else {
          foreach ($field_values as $k => $value) {
            $query_params[] = array(
              $pardot_key => reset($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])) . '&';
    }
    $url = $storage['pardot_mapping']->post_url;
    $options = array(
      'timeout' => 5,
      'query' => $query_string,
    );
    $response = $result = NULL;
    try {
      $client = \Drupal::httpClient();
      $response = $client
        ->request('POST', $url, $options);
      $result = $response
        ->getBody();
    } catch (RequestException $e) {
      watchdog_exception('pardot', $e);
    }

    // Log the submission.
    $context = array(
      'timestamp' => time(),
      'response' => $response,
      'result' => $result,
    );
    if (!empty($response) && $response
      ->getStatusCode() == '200') {
      \Drupal::logger('pardot')
        ->notice('Submitted Pardot Contact Form Map @label.', array(
        '@label' => $storage['pardot_mapping']->label,
      ), $context);
    }
    else {
      \Drupal::logger('eloqua_entity_bridge')
        ->error('Error submitting Pardot Contact Form Map @label.', array(
        '@label' => $storage['pardot_mapping']->label,
      ), $context);
    }
  }
}