public function ChecklistapiChecklist::saveProgress in Checklist API 8
Saves checklist progress.
Parameters
array $values: A multidimensional array of form state checklist values.
See also
checklistapi_checklist_form_submit()
File
- src/
ChecklistapiChecklist.php, line 245
Class
- ChecklistapiChecklist
- Defines the checklist class.
Namespace
Drupal\checklistapiCode
public function saveProgress(array $values) {
$user = \Drupal::currentUser();
$time = time();
$num_changed_items = 0;
$progress = [
'#changed' => $time,
'#changed_by' => $user
->id(),
'#completed_items' => 0,
'#items' => [],
];
// 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['#items'][$item_key]) ? $this->savedProgress['#items'][$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 = [
'#completed' => $time,
'#uid' => $user
->id(),
];
$num_changed_items++;
}
$progress['#items'][$item_key] = $new_item;
}
else {
// Item is unchecked.
if ($old_item) {
// Item was previously checked.
$num_changed_items++;
}
}
}
}
// 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 details. This reduces non-substantive changes to
// configuration files.
ksort($progress);
$this->storage
->setSavedProgress($progress);
\Drupal::messenger()
->addMessage(\Drupal::translation()
->formatPlural($num_changed_items, '%title progress has been saved. 1 item changed.', '%title progress has been saved. @count items changed.', [
'%title' => $this->title,
]));
}