MDL-39692 grade: Ability to delete letter boundary

This commit is contained in:
Huy Hoang 2014-11-10 12:14:31 +08:00 committed by Frederic Massart
parent 683d7de4d1
commit 1d693611e5

View File

@ -146,15 +146,23 @@ if (!$edit) {
if ($letter == '') {
continue;
}
// The keys need to be strings so floats are not truncated.
$letters[strval($data->$gradeboundaryname)] = $letter;
}
}
krsort($letters, SORT_NUMERIC);
$boundary = floatval($data->$gradeboundaryname);
$old_ids = array();
if ($records = $DB->get_records('grade_letters', array('contextid' => $context->id), 'lowerboundary ASC', 'id')) {
$old_ids = array_keys($records);
if ($boundary < 0 || $boundary > 100) {
continue; // skip if out of range
}
// The keys need to be strings so floats are not truncated.
$letters[number_format($boundary, 5)] = $letter;
}
}
$pool = array();
if ($records = $DB->get_records('grade_letters', array('contextid' => $context->id), 'lowerboundary ASC')) {
foreach ($records as $r) {
// will re-use the lowerboundary to avoid duplicate during the update process
$pool[number_format($r->lowerboundary, 5)] = $r;
}
}
foreach ($letters as $boundary => $letter) {
@ -163,16 +171,29 @@ if (!$edit) {
$record->lowerboundary = $boundary;
$record->contextid = $context->id;
if ($old_id = array_pop($old_ids)) {
$record->id = $old_id;
// re-use the existing boundary to avoid key constraint
if (isset($pool[$boundary])) {
// skip if the letter has been assigned to the boundary already
if ($letter == $pool[$boundary]->letter) {
unset($pool[$boundary]); // take it out of the pool
}
else {
$record->id = $pool[$boundary]->id;
$DB->update_record('grade_letters', $record);
unset($pool[$boundary]); // remove the ID from the pool
}
}
else if ($candidate = array_pop($pool)) {
$record->id = $candidate->id;
$DB->update_record('grade_letters', $record);
} else {
$DB->insert_record('grade_letters', $record);
}
}
foreach($old_ids as $old_id) {
$DB->delete_records('grade_letters', array('id' => $old_id));
// delete the unused records
foreach($pool as $leftover) {
$DB->delete_records('grade_letters', array('id' => $leftover->id));
}
redirect($returnurl);