Files
booking/booking.variety_admin.inc
2018-07-13 15:11:05 +10:00

904 lines
35 KiB
PHP

<?php
/**
* @file
* Admin pages for configuring a variety session
* NOTE: This feature is not complete and probably never will be
*/
function booking_variety_admin() {
global $event;
//see http://www.jaypan.com/blog/themeing-drupal-7-forms-tables-checkboxes-or-radios
// tableselect with text fields http://drupal.stackexchange.com/questions/75950/tableselect-with-textfields/82763#82763
// inline edit buttons http://drupal.stackexchange.com/questions/31942/how-do-i-add-an-edit-button-on-each-row-of-a-tableselect-form-element
// tabledrag example http://dropbucket.org/node/204
$form = array ();
$options = array ();
$result = db_query("SELECT * from {booking_variety_timeslots}");
$header = array (
'eid' => t('Event'),
'tid' => t('Timeslot ID'),
'booking_variety_time_descrip' => t('Description'),
'booking_variety_status' => t('Status'),
'booking_variety_start' => t('Timeslot Start'),
'booking_variety_end' => t('Timeslot End'),
'variety_edit' => t('Edit Timeslot'),
'variety_session_list' => t('List Sessions'),
'variety_session_add' => t('Add Session'),
'variety_session_csv' => t('CSV Report'),
);
foreach($result as $data) {
$options[$data->tid] = array (
'eid' => $event->booking_eventname,
'tid' => $data->tid,
'booking_variety_time_descrip' => $data->booking_variety_time_descrip,
'booking_variety_status' => $data->booking_variety_status == 1 ? "Enabled" : "Disabled",
'booking_variety_start' => date("Y-m-d H:i", $data->booking_variety_start),
'booking_variety_end' => date("Y-m-d H:i", $data->booking_variety_end),
'variety_edit' => l('Edit Timeslot', t('admin/booking/variety/!tid/edit', array('!tid' => $data->tid))),
'variety_session_list' => l('List Sessions', t('admin/booking/variety/!tid/session/list', array('!tid' => $data->tid))),
'variety_session_add' => l('Add Session', t('admin/booking/variety/!tid/session/create', array('!tid' => $data->tid))),
'variety_session_csv' => l('CSV Report', t('admin/booking/variety/!tid/csv', array('!tid' => $data->tid))),
);
}
$form['table'] = array (
'#type' => 'tableselect',
'#header' => $header,
'#options' => $options,
'#multiple' => false,
);
return array (
'form' => $form,
);
}
/**
* Function to add a new variety session timeslot
*/
function booking_variety_timeslot_form($node, &$form_state, $create, $editid = 0) {
global $event;
$form = array ();
$prefix = "<p>Add a new variety session timeslot for the bookings module.</p>";
if ($create == true) {
$data = $node;
}
else {
//verify that $editid is a number
if (! preg_match('/^[0-9]+$/', $editid)) {
drupal_set_message("Error: Invalid variety ID supplied. Unable to update variety session information.", 'error', FALSE);
drupal_goto('admin/booking/variety');
return "";
}
$data = db_select ('booking_variety_timeslots', 'v')
->condition('v.tid', $editid, '=')
->fields('v')
->execute()
->fetchObject();
$prefix = t("<p>Update the !event variety session details.</p>", array('!event' => $event->booking_eventname));
//add this to the form in a hidden field so we can update the right event
$form['tid'] = array (
'#type' => 'hidden',
'#value' => $editid,
);
}
$form['booking_variety_time_descrip'] = array (
'#type' => 'textfield',
'#title' => t('The name of this variety session timeslot'),
'#size' => 60,
'#maxlength' => 150,
'#required' => TRUE,
'#default_value' => !empty($data->booking_variety_time_descrip) ? $data->booking_variety_time_descrip : '',
);
$form['booking_variety_status'] = array(
'#type' => 'checkbox',
'#title' => t('Make this variety session timeslot active'),
'#default_value' => !empty($data->booking_variety_status) ? $data->booking_variety_status : '',
);
$form['booking_variety_start'] = array(
'#type' => 'date_select',
'#title' => t('When will this variety session start'),
'#default_value' => empty($data->booking_variety_start) ? date("Y-m-d H:i:s") : date("Y-m-d H:i:s", $data->booking_variety_start),
'#date_format' => 'd/m/Y H:i',
'#date_label_position' => 'within',
'#date_year_range' => '0:+5'
);
$form['booking_variety_end'] = array(
'#type' => 'date_select',
'#title' => t('When will this variety session end?'),
'#default_value' => empty($data->booking_variety_end) ? date("Y-m-d H:i:s") : date("Y-m-d H:i:s", $data->booking_variety_end),
'#date_format' => 'd/m/Y H:i',
'#date_label_position' => 'within',
'#date_year_range' => '0:+5'
);
if ($create == true) {
$form['submit'] = array (
'#type' => 'submit',
'#value' => t('Create'),
);
}
else {
$form['Update'] = array (
'#type' => 'submit',
'#value' => t('Update'),
);
$form['Delete'] = array (
'#type' => 'submit',
'#value' => t('Delete'),
);
}
return array(
'first_para' => array (
'#type' => 'markup',
'#markup' => $prefix,
),
'form' => $form,
);
}
/**
* Function to submit data for a new variety session timeslot
*/
function booking_variety_timeslot_form_submit($form, &$form_state) {
global $event;
$values = $form_state['input'];
if ($form_state['values']['op'] == 'Create') {
db_insert('booking_variety_timeslots')
->fields(array(
'booking_eventid' => $event->eid,
'booking_variety_status' => $values['booking_variety_status'] == 1 ? 1 : 0,
'booking_variety_time_descrip' => $values['booking_variety_time_descrip'],
'booking_variety_start' => _datetime_array_to_ts($values['booking_variety_start']),
'booking_variety_end' => _datetime_array_to_ts($values['booking_variety_end']),
))
->execute();
}
elseif ($form_state['values']['op'] == 'Delete') {
//verify that tid is a number
if (! preg_match('/^[0-9]+$/', $values['tid'])) {
drupal_set_message("Error: Invalid variety timeslot ID supplied. Unable to delete entry.", 'error', FALSE);
return "";
}
$num_deleted = db_delete('booking_variety_timeslots')
->condition('tid', $values['tid'])
->execute();
$message = t("Successfully deleted !num row(s), corresponding to variety session timeslot '!desc'",
array('!num' => $num_deleted, '!desc' => $values['booking_variety_time_descrip']));
drupal_set_message($message, $type = 'status');
}
else {
//verify that booking_eid is a number
if (! preg_match('/^[0-9]+$/', $values['tid'])) {
drupal_set_message("Error: Invalid variety session timeslot ID supplied. Unable to update entry.", 'error', FALSE);
return "";
}
//update the event
db_update('booking_variety_timeslots')
->fields(array (
'booking_eventid' => $event->eid,
'booking_variety_time_descrip' => $values['booking_variety_time_descrip'],
'booking_variety_status' => $values['booking_variety_status'] == 1 ? 1 : 0,
'booking_variety_start' => _datetime_array_to_ts($values['booking_variety_start']),
'booking_variety_end' => _datetime_array_to_ts($values['booking_variety_end']),
))
->condition('tid', $values['tid'])
->execute();
}
$form_state['redirect'] = array('admin/booking/variety');
}
/**
* Function to create or edit a variety session
*/
function booking_variety_create_session_form($node, &$form_state, $create = TRUE, $timeslot_id = 0, $session_id = 0) {
global $event;
$form = array ();
$prefix = "";
//add this to the form in a hidden field so we can update the right event
$form['tid'] = array (
'#type' => 'hidden',
'#value' => $timeslot_id,
);
if ($create == TRUE) {
$data = $node;
$prefix = "<p>Add a new variety session to the specified variety session timeslot for the bookings module.</p>";
}
else {
//verify that $timeslot_id is a number
if (! preg_match('/^[0-9]+$/', $timeslot_id)) {
drupal_set_message("Error: Invalid timeslot ID supplied. Unable to update specified variety session.", 'error', FALSE);
drupal_goto('admin/booking/variety');
return "";
}
//verify that $session_id is a number
if (! preg_match('/^[0-9]+$/', $session_id)) {
drupal_set_message("Error: Invalid session ID supplied. Unable to update specified variety session.", 'error', FALSE);
drupal_goto('admin/booking/variety');
return "";
}
$prefix = t("<p>Update the variety session defintion.</p>");
$data = db_query("SELECT * FROM {booking_variety_sessions} WHERE vid = :id", array(':id' => $session_id))
->fetchObject();
//add this to the form in a hidden field so we can update the right variety session
$form['booking_session_id'] = array(
'#type' => 'hidden',
'#value' => $session_id,
);
}
//define the form for variety session configuration if we're not deleting a session
if(!isset($form_state['storage']['confirm'])) {
$form[] = array (
'first_heading' => array(
'#type' => 'markup',
'#markup' => $prefix,
),
);
$form['booking_variety_descrip'] = array (
'#type' => 'textfield',
'#title' => t('The name of the variety session to add to this timeslot'),
'#size' => 60,
'#maxlength' => 150,
'#required' => TRUE,
'#default_value' => !empty($data->booking_variety_descrip) ? $data->booking_variety_descrip : '',
);
$form['booking_variety_status'] = array(
'#type' => 'checkbox',
'#title' => t('Make this variety session active?'),
'#default_value' => !empty($data->booking_variety_status) ? $data->booking_variety_status : '',
);
$form['booking_variety_maxsize'] = array (
'#type' => 'textfield',
'#title' => t('The maximum number of people permitted in this variety session'),
'#size' => 5,
'#maxlength' => 5,
'#required' => TRUE,
'#default_value' => !empty($data->booking_variety_maxsize) ? $data->booking_variety_maxsize : '0',
);
if ($create == true) {
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Create Session'),
);
}
else {
$form['Update'] = array(
'#type' => 'submit',
'#value' => t('Update Session'),
);
$form['Delete'] = array(
'#type' => 'submit',
'#value' => t('Delete Session'),
);
}
return array (
'form' => $form,
);
} //end checking for delete confirmation
else {
return confirm_form($form, "Are you sure you wish to delete variety session definition with id " . $session_id . "?",
current_path(), NULL, "Delete Session");
}
}
/**
* Function submit data for a variety session timeslot
*/
function booking_variety_create_session_form_submit($form, &$form_state) {
global $event;
$values = $form_state['input'];
$timeslot_id = $values['tid'];
$redirect_path = "admin/booking/variety/$timeslot_id/session/list";
//if we're deleting, add the confirmation to the form if it hasn't been defined yet
if($form_state['values']['op'] == 'Delete Session' && (!isset($form_state['storage']['confirm']))) {
//watchdog('booking_debug', "<pre>Variety session deletion confirmation being set:\n@info</pre>", array('@info' => print_r( $form_state, true)));
$form_state['storage']['confirm'] = TRUE;
$form_state['rebuild'] = TRUE;
}
elseif ($form_state['values']['op'] == 'Delete Session') {
//delete the variety session
watchdog('booking', "Deleting variety session ID !sid", array('!sid' => $values['booking_session_id']));
db_delete('booking_variety_sessions')
->condition('vid', $values['booking_session_id'])
->execute();
//TODO : Remove this variety session from anyone registered for it
drupal_set_message('Deleted variety session id ' . $values['booking_session_id'] );
$form_state['redirect'] = $redirect_path;
}
elseif ($form_state['values']['op'] == 'Update Session') {
$result = db_update('booking_variety_sessions')
->fields(array(
'booking_eventid' => $event->eid,
'booking_variety_descrip' => $values['booking_variety_descrip'],
'booking_variety_status' => $values['booking_variety_status'] == 1 ? 1 : 0,
'booking_variety_maxsize' => $values['booking_variety_maxsize'],
))
->condition('vid', $values['booking_session_id'] )
->execute();
drupal_set_message('Updated variety session id ' . $values['booking_session_id'] );
$form_state['redirect'] = $redirect_path;
}
elseif ($form_state['values']['op'] == 'Create Session') {
db_insert('booking_variety_sessions')
->fields(array(
'booking_eventid' => $event->eid,
'booking_variety_timeslot_id' => $values['tid'],
'booking_variety_status' => $values['booking_variety_status'] == 1 ? 1 : 0,
'booking_variety_descrip' => $values['booking_variety_descrip'],
'booking_variety_maxsize' => $values['booking_variety_maxsize'],
'booking_variety_regncount' => 0,
))
->execute();
drupal_set_message('Created new variety session definition');
$form_state['redirect'] = $redirect_path;
}
}
/**
* Function to list all variety sessions for specified timeslot
*/
function booking_variety_list_session_form($node, &$form_state, $timeslot_id = 0)
{
global $event;
$form = array ();
$options = array ();
$data = $node;
//verify that $editid is a number
if (! preg_match('/^[0-9]+$/', $timeslot_id)) {
drupal_set_message("Error: Invalid variety ID supplied. Unable to select variety session information.", 'error', FALSE);
drupal_goto('admin/booking/variety');
return "";
}
$prefix = t("<p>!link</p>",
array ('!link' => l('Add New Variety Session', "admin/booking/variety/$timeslot_id/session/create")));
$query = db_select ('booking_variety_sessions', 'v');
$query->join('booking_variety_timeslots', 't', 'v.booking_variety_timeslot_id = t.tid');
$query->condition('v.booking_variety_timeslot_id', $timeslot_id, '=')
->fields('v')
->fields('t', array('booking_variety_time_descrip'));
$result = $query->execute();
//watchdog('booking', 'Variety session query: @info', array ('@info' => (string)$query));
$header = array (
'variety_timeslot' => t('Variety Timeslot'),
'booking_variety_descrip' => t('Variety Session Description'),
'booking_variety_status' => t('Status'),
'booking_variety_maxsize' => t('Maximum Capacity'),
'booking_variety_regncount' => t('Current Registration Count'),
'variety_edit' => t('Edit Session')
);
foreach($result as $data) {
$options[$data->vid] = array (
'variety_timeslot' => $data->booking_variety_time_descrip,
'booking_variety_descrip' => $data->booking_variety_descrip,
'booking_variety_status' => $data->booking_variety_status == 1 ? 'Active' : 'Inactive',
'booking_variety_maxsize' => $data->booking_variety_maxsize,
'booking_variety_regncount' => $data->booking_variety_regncount,
'variety_edit' => l('Edit Session', t('admin/booking/variety/!tid/session/!vid/edit',
array('!tid' => $timeslot_id, '!vid' => $data->vid))),
);
}
$form['table'] = array (
'#type' => 'tableselect',
'#header' => $header,
'#options' => $options,
'#multiple' => false,
);
return array (
'first_para' => array (
'#type' => 'markup',
'#markup' => $prefix,
),
'form' => $form,
);
}
/**
* Function to generate table listing all variety session registrations
*/
function booking_variety_sessions_view_summary() {
global $event;
$output = "";
$header = array('First Name', 'Last Name');
$rows = array();
$attributes = array('style' => 'max-width:100%');
//get variety session timeslot definitions
$timeslot_query = db_select('booking_variety_timeslots', 't');
$timeslot_query->condition('t.booking_eventid', $event->eid, '=')
->fields('t')
->orderBy('t.booking_variety_start');
$timeslot_list = $timeslot_query->execute()->fetchAllAssoc('tid');
//watchdog('booking_debug', "<pre>Variety Session Report timeslots:\n@info</pre>", array('@info' => print_r( $timeslot_list, true)));
//get vareity session definitions
$sessions_query = db_query("SELECT * FROM {booking_variety_sessions} WHERE booking_eventid = :eid",
array(':eid' => $event->eid));
$sessions = $sessions_query->fetchAllAssoc('vid');
//watchdog('booking_debug', "<pre>Variety Session Report sessions:\n@info</pre>", array('@info' => print_r( $sessions, true)));
foreach ($timeslot_list as $timeslot) {
$header[] = $timeslot->booking_variety_time_descrip;
}
// Add a link at the end to edit a variety session registration
$header[] = "Edit Session Registrations";
$person_query = db_query("SELECT * FROM {booking_person_view} WHERE booking_status = 1 " .
" ORDER BY booking_lastname, booking_firstname")->fetchAllAssoc('nid');
//loop through each matching person
foreach ($person_query as $person) {
//add the name to an array for this line
$newline = array($person->booking_firstname, $person->booking_lastname);
$session_ids = drupal_json_decode($person->booking_variety_ids);
foreach ($timeslot_list as $timeslot) {
if (isset($session_ids[$timeslot->tid])) {
//get details of the person's variety session for this timeslot
$vid = $session_ids[$timeslot->tid];
//watchdog('booking_debug', 'Person @nid in timeslot @tid registered for session id @vid', array(
// '@nid' => $person->nid, '@tid' => $timeslot->tid, '@vid' => $vid,
//));
// in case the person is somehow registered for a session that no longer exists
if (isset($sessions[$vid])) {
$text = $sessions[$vid]->booking_variety_descrip;
}
else {
$text = "";
}
$newline[] = $text;
}
else {
$newline[] = "";
}
} //end iterate variety session timeslot list
$newline[] = l('Edit', t('admin/booking/variety/registration/!nid/edit', array('!nid' => $person->nid)));
//add the line to the array of rows
$rows[] = $newline;
} //end iterate person list
//output everything
$output .= t("<h3>!event Variety Session Registrations</h3>", array('!event' => $event->booking_eventname));
$output .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => $attributes));
return $output;
}
/**
* Function to generate a CSV file listing the session membership for the specified variety session timeslot
*/
function booking_varietysessions_csv_report($timeslot_id) {
global $event;
$data = array();
$rows = array();
//include_once("./libraries/xlsxwriter.class.php");
module_load_include('php', 'booking', 'libraries/xlsxwriter.class');
//verify that $timeslot_id is a number
if (! preg_match('/^[0-9]+$/', $timeslot_id)) {
drupal_set_message("Error: Invalid variety session timeslot ID '" . $timeslot_id . "' supplied.", 'error', FALSE);
drupal_goto('admin/booking/variety');
return "";
}
//retrieve the sessions for the specified timeslot
$db_and = db_and();
$db_and->condition('v.booking_eventid', $event->eid, '=');
$db_and->condition('v.booking_variety_timeslot_id', $timeslot_id, '=');
$variety_sessions = db_select('booking_variety_sessions', 'v')
->condition($db_and)
->fields('v')
->execute()
->fetchAllAssoc('vid');
//watchdog('booking_debug', 'booking_varietysessions_csv_report variety sessions: <pre>@info</pre>', array('@info' => print_r( $variety_sessions, true)));
if (! $variety_sessions) {
drupal_set_message("Error: Could not find matching variety session timeslot. Unable to view session membership.", 'error', FALSE);
drupal_goto('admin/booking/variety');
return "";
}
//set options for the CSV file
$csv = '';
$delimiter = ',';
$enclosure = '"';
$encloseAll = false;
$nullToMysqlNull = true;
$delimiter_esc = preg_quote($delimiter, '/');
$enclosure_esc = preg_quote($enclosure, '/');
// List of style options at https://github.com/mk-j/PHP_XLSXWriter/issues/198
$header_style = array( 'border'=>'bottom','border-style'=>'thin', 'border-color'=>'#000000',
'valign'=>'top', 'font-style' => 'bold');
//get the list of variety session memberships
$session_members_query = db_query("SELECT r.*, p.* FROM {booking_variety_regn} r
inner join {booking_person} p on p.nid = r.booking_person_nid
WHERE p.booking_eventid = :eid ORDER BY r.rid",
array(':eid' => $event->eid));
$session_members = $session_members_query->fetchAll();
// Check if we had no data added, that means there were no people in this study group
if (! $session_members) {
drupal_set_message("Error: Variety Session timeslot $timeslot_id has no members assigned.", 'error', FALSE);
drupal_goto('admin/booking/variety');
return "";
}
//watchdog('booking_debug', 'booking_varietysessions_csv_report session members: <pre>@info</pre>', array('@info' => print_r( $session_members, true)));
// Organise people by session ID
foreach ($session_members as $member) {
$session_ids = drupal_json_decode($member->booking_variety_ids);
//watchdog('booking_debug', 'booking_varietysessions_csv_report person session ids: <pre>@info</pre>', array('@info' => print_r( $session_ids, true)));
//get the session id that matches our timeslot if it exists
if (isset($session_ids[$timeslot_id])) {
$sid = $session_ids[$timeslot_id];
if (! isset($data[$sid])) {
$data[$sid] = array();
}
//add the spaces and put this element in the right array
$text = array($member->booking_firstname, $member->booking_lastname);
$data[$sid][] = implode(' ', $text);
}
}
//watchdog('booking_debug', "<pre>Study Group CSV Report\n@info</pre>", array('@info' => print_r( $data_array, true)));
// Calculate column headings and spreadsheet layout
$header_array = array_keys($data);
$maximums = array();
$column_headings = array();
foreach ($header_array as $column) {
$maximums[] = count($data[$column]);
//make the column headings a bit more user friendly
$heading = $variety_sessions[$column]->booking_variety_descrip;
//enclose $heading if necessary
//if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $heading ) ) {
// $heading = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $heading) . $enclosure;
//}
// Adjusted for excel, assume each column is just a string
//$column_headings[] = array($heading => 'string');
$column_headings[$heading] = 'string';
}
watchdog('booking_debug', "<pre>Variety session spreadsheet columns\n@info</pre>",
array('@info' => print_r( $column_headings, true)));
// Calculate each row based on column headings
for ($i = 0; $i < max($maximums); $i++) {
$output = array();
foreach ($header_array as $column) {
$field = isset($data[$column][$i]) ? $data[$column][$i] : '';
//enclose $field if necessary
//if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
// $output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
//}
//else {
$output[] = $field;
//}
} //loop through columns
$rows[] = $output;
//$row = implode($delimiter, $output) . "\n";
//$csv .= $row;
}
watchdog('booking_debug', "<pre>Variety session spreadsheet rows\n@info</pre>",
array('@info' => print_r( $rows, true)));
// Create headers for Excel spreadsheet
$filename = 'bookings-timeslot-' . $timeslot_id . '-variety-sessions-' . format_date(time(), 'custom', 'Y-m-d-His') . ".xlsx";
header('Content-disposition: attachment; filename="'.XLSXWriter::sanitize_filename($filename).'"');
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$sheetname = "Variety Session " . $timeslot_id;
$writer = new XLSXWriter();
$writer->setFontName('Calibri'); //default document font name
$writer->setAuthor($event->booking_eventname);
//Add the header row
$writer->writeSheetHeader($sheetname, $column_headings, $header_style);
//Add the data
foreach($rows as $row) {
$writer->writeSheetRow($sheetname, $row);
}
$writer->writeToStdOut();
exit(0);
}
/**
* Build the admin form for editing variety session registrations
*/
function booking_variety_regn_edit_form($node, &$form_state, $nid)
{
global $event;
$form = array();
$data = $node;
$redirect_path = "admin/booking/variety/report";
//verify that $variety_regn_id is a number
if (! preg_match('/^[0-9]+$/', $nid)) {
drupal_set_message("Error: Invalid variety session registration ID supplied. Unable to update variety session registration for user.", 'error', FALSE);
drupal_goto($redirect_path);
return "";
}
$person = db_query("SELECT * FROM {booking_person_view} WHERE nid = :nid",
array(':nid' => $nid))->fetchObject();
if (! $person) {
drupal_set_message("Error: Could not find matching person. Unable to edit variety session registrations.", 'error', FALSE);
drupal_goto($redirect_path);
return "";
}
$session_ids = drupal_json_decode($person->booking_variety_ids);
$prefix = t("<h3>Edit variety session registration for !first !last.<br /></h3>",
array('!first' => $person->booking_firstname, '!last' => $person->booking_lastname));
// Query the variety timeslot table so we know how many select elements to create
$timeslot_query = db_select('booking_variety_timeslots', 'v');
$timeslot_query->condition('v.booking_eventid', $event->eid, '=')
->fields('v')
->orderBy('v.booking_variety_start');
$timeslot_result = $timeslot_query->execute();
// --- Form starts here ---
//add the person nid to the form in a hidden field so we can update the right person later
$form['nid'] = array (
'#type' => 'hidden',
'#value' => $nid,
);
//define the form for variety session configuration if we're not deleting a session
if(!isset($form_state['storage']['confirm'])) {
$form[] = array (
'first_heading' => array(
'#type' => 'markup',
'#markup' => $prefix,
),
);
$form['variety-sessions'] = array(
'#type' => 'fieldset',
'#title' => 'Select Variety Sessions',
'#prefix' => '<div id="booking_variety_session_fieldset_wrapper">',
'#suffix' => '</div>'
);
//for each entry in the variety timeslot table, create a new form select item
foreach($timeslot_result as $timeslot) {
$fieldname = 'select-variety-' . $timeslot->tid;
$default = isset($session_ids[$timeslot->tid]) ? $session_ids[$timeslot->tid] : '--';
$default_value = isset($form_state['values'][$fieldname]) ? $form_state['values'][$fieldname] : $default;
//create the form element for this timeslot
$form['variety-sessions'][$fieldname] = array(
'#type' => 'select',
'#title' => t('Variety Session: ' . $timeslot->booking_variety_time_descrip),
'#required' => TRUE,
'#default_value' => $default_value,
'#options' => _booking_get_variety_timeslot_options($timeslot->tid),
);
}
$form['Update'] = array(
'#type' => 'submit',
'#value' => t('Update Session Registration'),
);
$form['Delete'] = array(
'#type' => 'submit',
'#value' => t('Delete Session Registration'),
);
return array (
'form' => $form,
);
} //end checking for delete confirmation
else {
return confirm_form($form, "Are you sure you wish to delete all variety session registrations for person id " . $nid . "?",
current_path(), NULL, "Delete Session Registration");
}
}
/**
* Function submit data for editing a variety session registration for a person
*/
function booking_variety_regn_edit_form_submit($form, &$form_state) {
global $event;
$values = $form_state['input'];
$booking_variety_ids = array();
$redirect_path = "admin/booking/variety/report";
//get a list of timeslot IDs from matching form values
$variety_timeslot_ids = preg_filter('/^select-variety-(\d+)/', '$1', array_keys( $values ));
//build an associative array based on selections
foreach ($variety_timeslot_ids as $id) {
$selected_session_id = $values['select-variety-' . $id];
// Don't try and check availablity for a select element that is still on the default value
if ($selected_session_id == 0) {
continue;
}
//store the selected variety sessions in an array of IDs
$booking_variety_ids[$id] = $selected_session_id;
}
watchdog('booking_debug', "<pre>Variety session IDs from edit form:\n@info</pre>", array('@info' => print_r( $booking_variety_ids, true)));
// Get the previous variety session IDs so we can check for changes
$person = db_query("SELECT * FROM {booking_person_view} WHERE nid = :nid",
array(':nid' => $values['nid']))->fetchObject();
$previous_variety_ids = drupal_json_decode($person->booking_variety_ids);
//if we're deleting, add the confirmation to the form if it hasn't been defined yet
if($form_state['values']['op'] == 'Delete Session Registration' && (!isset($form_state['storage']['confirm']))) {
//watchdog('booking_debug', "<pre>Variety session registration deletion confirmation being set:\n@info</pre>", array('@info' => print_r( $form_state, true)));
$form_state['storage']['confirm'] = TRUE;
$form_state['rebuild'] = TRUE;
}
elseif ($form_state['values']['op'] == 'Delete Session Registration') {
//delete the variety session
watchdog('booking', "Deleting variety session registration for person ID !nid", array('!nid' => $values['nid']));
//decremement regn count for this person's variety sessions
foreach ($previous_variety_ids as $previous_tid => $previous_sid) {
watchdog('booking_debug', 'Person @nid in timeslot @tid is no longer registered for any variety sessions so reducing count for @vid by 1', array(
'@nid' => $values['nid'], '@tid' => $previous_tid, '@vid' => $previous_sid,
));
// reduce regn count for old session
db_update('booking_variety_sessions')
->expression('booking_variety_regncount', 'booking_variety_regncount - :count', array(':count' => 1))
->condition('vid', $previous_sid)
->execute();
}
//delete this person's entry in the session registration table
db_delete('booking_variety_regn')
->condition('booking_person_nid', $values['nid'])
->execute();
drupal_set_message('Deleted variety session registration for person id ' . $values['nid'] );
$form_state['redirect'] = $redirect_path;
}
elseif ($form_state['values']['op'] == 'Update Session Registration') {
// iterate over the new list comparing to the old list
foreach ($booking_variety_ids as $new_tid => $new_sid) {
//check if there was a previous session ID for this person in this timeslot
if (! isset($previous_variety_ids[$new_tid])) {
watchdog('booking_debug', 'Person @nid in timeslot @tid had no previous session id registered but is now @new.', array(
'@nid' => $values['nid'], '@tid' => $new_tid, '@new' => $new_sid));
// increase regn count for new session
db_update('booking_variety_sessions')
->expression('booking_variety_regncount', 'booking_variety_regncount + :count', array(':count' => 1))
->condition('vid', $new_sid)
->execute();
}
else {
$previous_sid = $previous_variety_ids[$new_tid];
//compare session id in this timeslot to the previous value
if ($new_sid != $previous_sid) {
watchdog('booking_debug', 'Person @nid in timeslot @tid previously registered for session id @vid but new value is @new', array(
'@nid' => $values['nid'], '@tid' => $new_tid, '@vid' => $previous_sid, '@new' => $new_sid));
// if variety session has changed then update the counts for old and new
if ($new_sid != $previous_sid) {
// reduce regn count for old session
watchdog('booking_debug', 'Person @nid in timeslot @tid is no longer registered for variety session @vid so reducing count by 1', array(
'@nid' => $values['nid'], '@tid' => $new_tid, '@vid' => $previous_sid));
db_update('booking_variety_sessions')
->expression('booking_variety_regncount', 'booking_variety_regncount - :count', array(':count' => 1))
->condition('vid', $previous_sid)
->execute();
// increase regn count for new session
watchdog('booking_debug', 'Person @nid in timeslot @tid is now registered for variety session @vid so increasing count by 1', array(
'@nid' => $values['nid'], '@tid' => $new_tid, '@vid' => $new_sid));
db_update('booking_variety_sessions')
->expression('booking_variety_regncount', 'booking_variety_regncount + :count', array(':count' => 1))
->condition('vid', $new_sid)
->execute();
}
}
else {
watchdog('booking_debug', 'Person @nid in timeslot @tid has not changed variety session @vid', array(
'@nid' => $values['nid'], '@tid' => $new_tid, '@vid' => $new_sid));
}
}
}
//iterate over the old list comparing to the new list in case there are regn counts we need to decrease
if (isset($previous_variety_ids)) {
foreach ($previous_variety_ids as $previous_tid => $previous_sid) {
if (! isset($booking_variety_ids[$previous_tid])) {
watchdog('booking_debug', 'Person @nid in timeslot @tid is no longer registered for a variety session so reducing count for @vid by 1', array(
'@nid' => $values['nid'], '@tid' => $previous_tid, '@vid' => $previous_sid,
));
// reduce regn count for old session
db_update('booking_variety_sessions')
->expression('booking_variety_regncount', 'booking_variety_regncount - :count', array(':count' => 1))
->condition('vid', $previous_sid)
->execute();
}
}
}
// See if this person ever had a variety session registration
$update_or_insert_check = db_query("SELECT * FROM {booking_variety_regn} " .
"WHERE booking_person_nid = :nid",
array(':nid' => $values['nid'],
))->fetchObject();
if (! $update_or_insert_check) {
// create new variety session registration information for this person
$result = db_insert('booking_variety_regn')
->fields(array(
'booking_person_nid' => $values['nid'],
'booking_variety_ids' => drupal_json_encode($booking_variety_ids),
))
->execute();
watchdog('booking', "Created variety session registration for person ID !nid", array('!nid' => $values['nid']));
}
else {
// update the session registration information for this person
$result = db_update('booking_variety_regn')
->fields(array(
'booking_variety_ids' => drupal_json_encode($booking_variety_ids),
))
->condition('booking_person_nid', $values['nid'])
->execute();
watchdog('booking', "Updated variety session registration for person ID !nid", array('!nid' => $values['nid']));
}
// Finished, redirect to original table
$form_state['redirect'] = $redirect_path;
}
}