You are here

public function ChecklistapiChecklist::saveProgress in Checklist API 7

Saves checklist progress to a Drupal variable.

Parameters

array $values: A multidimensional array of form state checklist values.

See also

checklistapi_checklist_form_submit()

File

lib/Drupal/checklistapi/ChecklistapiChecklist.php, line 203
Class for Checklist API checklists.

Class

ChecklistapiChecklist
Defines the checklist class.

Code

public function saveProgress(array $values) {
  global $user;
  $time = time();
  $num_changed_items = 0;
  $progress = array(
    '#changed' => $time,
    '#changed_by' => $user->uid,
    '#completed_items' => 0,
  );

  // Loop through groups.
  foreach ($values as $group_key => $group) {
    if (!is_array($group)) {
      continue;
    }

    // Loop through items.
    foreach ($group as $item_key => $item) {
      $definition = checklistapi_get_checklist_info($this->id);
      if (!in_array($item_key, array_keys($definition[$group_key]))) {

        // This item wasn't in the checklist definition. Don't include it with
        // saved progress.
        continue;
      }
      $old_item = !empty($this->savedProgress[$item_key]) ? $this->savedProgress[$item_key] : 0;
      if ($item == 1) {

        // Item is checked.
        $progress['#completed_items']++;
        if ($old_item) {

          // Item was previously checked. Use saved value.
          $new_item = $old_item;
        }
        else {

          // Item is newly checked. Set new value.
          $new_item = array(
            '#completed' => $time,
            '#uid' => $user->uid,
          );
          $num_changed_items++;
        }
      }
      else {

        // Item is unchecked.
        $new_item = 0;
        if ($old_item) {

          // Item was previously checked.
          $num_changed_items++;
        }
      }
      $progress[$item_key] = $new_item;
    }
  }

  // Sort array elements alphabetically so changes to the order of items in
  // checklist definitions over time don't affect the order of elements in the
  // saved progress variable. This simplifies use with Strongarm.
  ksort($progress);
  variable_set($this
    ->getSavedProgressVariableName(), $progress);
  drupal_set_message(format_plural($num_changed_items, '%title progress has been saved. 1 item changed.', '%title progress has been saved. @count items changed.', array(
    '%title' => $this->title,
  )));
}