MDL-63135 mod_choice: Added choice_get_user_response function

A new function to return choice answers records of a given user in a given choice activity.
This commit is contained in:
Shamim Rezaie
2018-09-06 20:15:03 +10:00
parent 4bd4b46070
commit b223dc24a6
2 changed files with 56 additions and 2 deletions
+15 -2
View File
@@ -1011,6 +1011,19 @@ function choice_print_overview($courses, &$htmlarray) {
}
/**
* Get responses of a given user on a given choice.
*
* @param stdClass $choice Choice record
* @param int $userid User id
* @return array of choice answers records
* @since Moodle 3.6
*/
function choice_get_user_response($choice, $userid) {
global $DB;
return $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $userid), 'optionid');
}
/**
* Get my responses on a given choice.
*
@@ -1019,8 +1032,8 @@ function choice_print_overview($courses, &$htmlarray) {
* @since Moodle 3.0
*/
function choice_get_my_response($choice) {
global $DB, $USER;
return $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $USER->id), 'optionid');
global $USER;
return choice_get_user_response($choice, $USER->id);
}
+41
View File
@@ -162,6 +162,47 @@ class mod_choice_lib_testcase extends externallib_advanced_testcase {
choice_user_submit_response($optionids2[0], $choice1, $USER->id, $course, $cm);
}
/**
* Test choice_get_user_response
* @return void
*/
public function test_choice_get_user_response() {
$this->resetAfterTest();
$this->setAdminUser();
// Setup test data.
$course = $this->getDataGenerator()->create_course();
$student = $this->getDataGenerator()->create_and_enrol($course, 'student');
$choice = $this->getDataGenerator()->create_module('choice', array('course' => $course->id));
$cm = get_coursemodule_from_instance('choice', $choice->id);
$choicewithoptions = choice_get_choice($choice->id);
$optionids = array_keys($choicewithoptions->option);
choice_user_submit_response($optionids[0], $choice, $student->id, $course, $cm);
$responses = choice_get_user_response($choice, $student->id);
$this->assertCount(1, $responses);
$response = array_shift($responses);
$this->assertEquals($optionids[0], $response->optionid);
// Multiple responses.
$choice = $this->getDataGenerator()->create_module('choice', array('course' => $course->id, 'allowmultiple' => 1));
$cm = get_coursemodule_from_instance('choice', $choice->id);
$choicewithoptions = choice_get_choice($choice->id);
$optionids = array_keys($choicewithoptions->option);
// Submit a response with the options reversed.
$selections = $optionids;
rsort($selections);
choice_user_submit_response($selections, $choice, $student->id, $course, $cm);
$responses = choice_get_user_response($choice, $student->id);
$this->assertCount(count($optionids), $responses);
foreach ($responses as $resp) {
$this->assertEquals(array_shift($optionids), $resp->optionid);
}
}
/**
* Test choice_get_my_response
* @return void