You are here

function availability_calendar_update_states in Availability Calendars 7.5

Same name and namespace in other branches
  1. 7.3 availability_calendar.inc \availability_calendar_update_states()
  2. 7.4 availability_calendar.inc \availability_calendar_update_states()

Updates the set of states.

Parameters

array $states: Array with the new state records (sid, css_class, label, weight, and is_available values).

Throws

\Exception

1 call to availability_calendar_update_states()
availability_calendar_admin_settings_submit in ./availability_calendar.admin.inc
Form submit callback for the admin_settings form.

File

./availability_calendar.inc, line 441

Code

function availability_calendar_update_states($states) {
  $table_name = 'availability_calendar_state';
  $existing_states = availability_calendar_get_states();
  foreach ($existing_states as $sid => $existing_state) {
    $delete = TRUE;
    foreach ($states as $state) {
      if (isset($state['sid']) && $state['sid'] == $sid) {
        $delete = FALSE;
        break;
      }
    }
    if ($delete) {

      // Cascading delete: delete availability referring to this sid.
      db_delete('availability_calendar_availability')
        ->condition('sid', $sid)
        ->execute();

      // Delete state itself.
      db_delete($table_name)
        ->condition('sid', $sid)
        ->execute();

      // @todo: update field instances (warning if something changes?)
      // this omission leads to a: Warning: Illegal offset type in form_type_checkboxes_value() (line 2229 of includes\form.inc).
      unset($existing_states[$sid]);
    }
  }
  foreach ($states as $state) {
    $sid = isset($state['sid']) ? $state['sid'] : NULL;
    unset($state['sid']);

    // Call the t() function to have the label added to the translation tables.
    t($state['label']);
    if (!empty($sid) && array_key_exists($sid, $existing_states)) {

      // Update
      db_update($table_name)
        ->fields($state)
        ->condition('sid', $sid, '=')
        ->execute();
    }
    else {

      // Insert, sid will be created.
      db_insert($table_name)
        ->fields($state)
        ->execute();
    }
  }
  drupal_static_reset('availability_calendar_get_states');
}