Skip to content

Instantly share code, notes, and snippets.

@psynaptic
Created February 21, 2012 13:56
Show Gist options
  • Save psynaptic/1876688 to your computer and use it in GitHub Desktop.
Save psynaptic/1876688 to your computer and use it in GitHub Desktop.
<?php
/**
* @file
* Custom functions for the congr site.
*/
/**
* Implements hook_form_alter().
*/
function congr_form_alter(&$form, $form_state, $form_id) {
// Add an additional validation handler.
if ($form_id == 'uc_cart_view_form') {
$form['#validate'][] = 'congr_afternoon_bookings_validate';
}
}
/**
* Additional validation handler for uc_cart_view_form.
*
* Checks afternoon tours for a maximum of 2 bookings.
*
* @see congr_form_alter()
*/
function congr_afternoon_bookings_validate(&$form, &$form_state) {
$congr_highlight_afternoon_fields = array();
$congr_max_afternoon = 0;
if (!empty($form['items'])) {
foreach ($form['items'] as $key => &$value) {
if (isset($value['nid']['#value'])) {
// Load the node of the corresponding item in the form.
$node = node_load($value['nid']['#value']);
// If the associated term tid is 476, add the quantity field of the
// item list to our maximum value.
if ($node->field_product_type['und'][0]['tid'] == 476) {
$congr_max_afternoon += $value['qty']['#default_value'];
// Collect a list of keys.
$congr_highlight_afternoon_fields[] = $key;
}
}
}
}
// If the maximum number of quantity items is more than 2.
if ($congr_max_afternoon > 2) {
$form_state['rebuild'] = TRUE;
foreach ($congr_highlight_afternoon_fields as $key => $value) {
$message = t('Please amend this item: %title.', array('%title' => $form['items'][$value]['title']['#markup']);
// If it is the first one, show the full message which is independent of
// a specific quantity field
if ($key == 0) {
form_set_error('', t('You have tried to buy %number items but the maximum you can buy is 2. See below for a list of items which you can possibly amend.', array('%number' => $congr_max_afternoon));
form_set_error('items]['. $value, $message);
}
// Do not show the message for the rest, only highlight the field.
else {
form_set_error('items][' . $value, $message);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment