Skip to content

Instantly share code, notes, and snippets.

@kvnm
Last active August 29, 2015 14:02
Show Gist options
  • Save kvnm/5472ecbfb7c325a5f5c4 to your computer and use it in GitHub Desktop.
Save kvnm/5472ecbfb7c325a5f5c4 to your computer and use it in GitHub Desktop.
Drupal snippet to validate whether a room (defined by a taxonomy term) has already been booked during the dates selected on a node form.
<?php
/**
* Implements hook_form_alter().
*
* Adds validation to Booking node forms.
*/
function custom_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'booking_node_form') {
$form['#validate'][] = 'custom_booking_validate';
}
}
/**
* Validation function for Booking node forms.
* Sends form_state values to custom_check_booking_availability().
*/
function custom_booking_validate($form, $form_state) {
$data = array(
'room' => $form_state['values']['field_room']['und'][0]['tid'],
'start' => $form_state['values']['field_booking_date']['und'][0]['value'],
'end' => $form_state['values']['field_booking_date']['und'][0]['value2'],
);
if (!isset($form_state['values']['field_booking_date']['und'][0]['timezone'])) {
$data['start'] = gmdate('Y-m-d H:i:s', strtotime($data['start']));
$data['end'] = gmdate('Y-m-d H:i:s', strtotime($data['end']));
}
if ($hit = custom_check_booking_availability($data)) {
form_set_error('field_room', 'The following event(s) are already booked in that time slot:' . $hit);
form_set_error('field_booking_date');
}
}
/**
* Validates availability of a Booking room, given a range of dates.
* Returns any Bookings already reserved in the given room at the given times.
*/
function custom_check_booking_availability($data) {
$query = db_select('node', 'n');
$query->leftJoin('field_data_field_room', 'r', 'r.entity_id = n.nid');
$query->leftJoin('field_data_field_booking_date', 'd', 'd.entity_id = n.nid');
$query
->condition('n.type', 'booking')
->condition('n.status', 1)
->condition('r.field_room_tid', $data['room'])
->condition('d.field_booking_date_value', $data['end'], '<=')
->condition('d.field_booking_date_value2', $data['start'], '>=')
->fields('n', array('title', 'nid'));
$result = $query->execute();
$hit = '';
foreach ($result as $row) {
$hit .= '<br />' . l($row->title, 'node/' . $row->nid);
}
if ($hit != '') {
return $hit;
}
else {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment