You are here

function commerce_registration_add_to_cart_validate in Commerce Registration 7.2

Custom validation handler for add to cart form. Checks if the product being added is available for registration before adding it to the cart. If it is not available, it is not added and a message is shown to the user.

1 string reference to 'commerce_registration_add_to_cart_validate'
commerce_registration_form_alter in ./commerce_registration.module
Implements hook_form_alter().

File

./commerce_registration.module, line 534
Commerce Registration module code.

Code

function commerce_registration_add_to_cart_validate($form, &$form_state) {
  global $user;
  $existing_registrations = NULL;
  $product_id = $form_state['values']['product_id'];
  $product = commerce_product_load($product_id);
  if (commerce_registration_product_has_registration_field($product_id)) {

    // Let the user know if they have an existing registration.
    // Check if there are some active states before running this query
    // or it will error out
    $registration_active_states = registration_get_active_states();
    if (!empty($registration_active_states)) {
      $query = new EntityFieldQuery();
      $existing_registrations = $query
        ->entityCondition('entity_type', 'registration')
        ->propertyCondition('entity_id', $product_id)
        ->propertyCondition('user_uid', $user->uid)
        ->propertyCondition('state', $registration_active_states)
        ->range(0, 1)
        ->execute();
    }
    else {
      watchdog('commerce_registration', t('Unable to lookup existing registrations for SKU: !sku because there are no registration active states set.', array(
        '!sku' => $product->sku,
      )));
    }
    if (!empty($existing_registrations)) {
      $message = 'You have already registered for %product.';
      $message_variables = array(
        '%product' => $product->title,
      );

      // If the user has access to view their own registrations, include a link
      // to the registration detail page.
      $registration = registration_load(reset($existing_registrations['registration'])->registration_id);
      if (registration_access('view', $registration)) {
        $message .= ' You can <a href="!uri">view your registration</a>.';
        $uri = $registration
          ->uri();
        $message_variables['!uri'] = url($uri['path']);
      }
      drupal_set_message(t($message, $message_variables));
    }

    // Check that registrations are open and the user has access.
    if (!registration_status('commerce_product', $product_id, TRUE) || !registration_register_page_access('commerce_product', $product)) {
      form_set_error('product_id', t('This product is not available for registration at this time.'));
      return FALSE;
    }
  }
  return TRUE;
}