You are here

function commerce_braintree_form_alter in Commerce Braintree 7

Implements hook_form_alter().

File

./commerce_braintree.module, line 166
Implementations of the Braintree payment gateway (http://braintreepayments.com) for drupal commerce.

Code

function commerce_braintree_form_alter(&$form, &$form_state, $form_id) {

  // If the current form ID is for a checkout form...
  if (strpos($form_id, 'commerce_checkout_form_') === 0 && $form_id != 'commerce_checkout_form_payment') {

    // And it specifies a valid checkout page...
    if (commerce_checkout_page_load(substr($form_id, 23))) {

      // And the current page's form includes the payment checkout pane...
      if (!empty($form['commerce_payment'])) {

        // Check to see if the currently selected payment method is Card on File
        // enabled (via the cardonfile boolean in its info array).
        $payment_method = commerce_payment_method_instance_load($form['commerce_payment']['payment_method']['#default_value']);
        if (!empty($payment_method['cardonfile'])) {

          // Load any existing card data for the current payment method instance
          // and user.
          $stored_cards = commerce_cardonfile_data_load_multiple($form_state['account']->uid, $payment_method['instance_id']);

          // Filter out expired cards.
          foreach ($stored_cards as $card_id => $card_data) {
            if ($card_data['card_exp_year'] < date('Y') || $card_data['card_exp_year'] == date('Y') && $card_data['card_exp_month'] < date('m')) {
              unset($stored_cards[$card_id]);
            }
          }

          // If we found any stored cards, show the options in the form.
          if (!empty($stored_cards)) {
            $element = variable_get('commerce_cardonfile_selector', 'radios');
            $options = commerce_cardonfile_options_list($stored_cards, $element);
            $form['commerce_payment']['payment_details']['cardonfile'] = array(
              '#type' => $element,
              '#title' => t('Select a stored credit card'),
              '#options' => $options,
              '#default_value' => key($options),
              '#weight' => -10,
            );

            // Be sure that the credit card form is not displayed.
            $form['commerce_payment']['payment_details']['credit_card']['#access'] = FALSE;

            // Add the CSS to hide a sole credit card icon if specified.
            if (variable_get('commerce_cardonfile_hide_cc_radio_button', TRUE)) {
              if (count($form['commerce_payment']['payment_method']['#options']) == 1) {
                $form['commerce_payment']['payment_method']['#attached']['css'][] = drupal_get_path('module', 'commerce_cardonfile') . '/theme/commerce_cardonfile.checkout.css';
              }
            }
          }
        }
      }
    }
  }
}