1
0
mirror of https://github.com/moodle/moodle.git synced 2025-04-25 10:26:17 +02:00

MDL-59368 groups: Inplace editing for users groups

This commit is contained in:
Damyon Wiese 2017-06-29 10:30:04 +08:00
parent 350700bf8b
commit 2fa35b8d16
9 changed files with 330 additions and 10 deletions
group
lang/en
lib
theme/boost/scss/moodle
user/classes

@ -0,0 +1,164 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Contains class core_group\output\user_groups_editable
*
* @package core_group
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_group\output;
use context_system;
use context_course;
use core_user;
use core_external;
/**
* Class to display list of user groups.
*
* @package core_group
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class user_groups_editable extends \core\output\inplace_editable {
/** @var $coursegroups */
private $coursegroups = null;
/** @var $context */
private $context = null;
/**
* Constructor.
*
* @param \stdClass|core_tag_tag $tag
*/
public function __construct($course, $context, $user, $coursegroups, $value) {
// Check capabilities to get editable value.
$editable = has_capability('moodle/course:managegroups', $context);
// Invent an itemid.
$itemid = $course->id . ':' . $user->id;
$value = json_encode($value);
// Remember these for the display value.
$this->coursegroups = $coursegroups;
$this->context = $context;
parent::__construct('core_group', 'user_groups', $itemid, $editable, $value, $value);
// Assignable groups.
$options = [];
foreach ($coursegroups as $group) {
$options[$group->id] = $group->name;
}
$attributes = ['multiple' => true];
$this->set_type_autocomplete($options, $attributes);
}
/**
* Export this data so it can be used as the context for a mustache template.
*
* @param \renderer_base $output
* @return \stdClass
*/
public function export_for_template(\renderer_base $output) {
// Set edithint and display value.
$this->edithint = get_string('editusersgroups', 'group');
$listofgroups = [];
$groupids = json_decode($this->value);
foreach ($groupids as $id) {
$listofgroups[] = format_string($this->coursegroups[$id]->name, true, ['context' => $this->context]);
}
$this->displayvalue = implode($listofgroups, ', ');
return parent::export_for_template($output);
}
/**
* Updates the value in database and returns itself, called from inplace_editable callback
*
* @param int $itemid
* @param mixed $newvalue
* @return \self
*/
public static function update($itemid, $newvalue) {
// Check caps.
// Do the thing.
// Return one of me.
// Validate the inputs.
list($courseid, $userid) = explode(':', $itemid, 2);
$courseid = clean_param($courseid, PARAM_INT);
$userid = clean_param($userid, PARAM_INT);
$groupids = json_decode($newvalue);
foreach ($groupids as $index => $groupid) {
$groupids[$index] = clean_param($groupid, PARAM_INT);
}
// Check user is enrolled in the course.
$context = context_course::instance($courseid);
core_external::validate_context($context);
if (!is_enrolled($context, $userid)) {
throw new coding_exception('User does not belong to the course');
}
// Check that all the groups belong to the course.
$coursegroups = groups_get_all_groups($courseid, 0, 0, 'g.*', true);
$byid = [];
foreach ($groupids as $groupid) {
if (!isset($coursegroups[$groupid])) {
throw new coding_exception('Group does not belong to the course');
}
$byid[$groupid] = $groupid;
}
$groupids = $byid;
// Check permissions.
require_capability('moodle/course:managegroups', $context);
// Process adds.
foreach ($groupids as $groupid) {
if (!isset($coursegroups[$groupid]->members[$userid])) {
// Add them.
groups_add_member($groupid, $userid);
// Keep this variable in sync.
$coursegroups[$groupid]->members[$userid] = $userid;
}
}
// Process removals.
foreach ($coursegroups as $groupid => $group) {
if (isset($group->members[$userid]) && !isset($groupids[$groupid])) {
if (groups_remove_member_allowed($groupid, $userid)) {
groups_remove_member($groupid, $userid);
unset($coursegroups[$groupid]->members[$userid]);
}
}
}
$course = get_course($courseid);
$user = core_user::get_user($userid);
return new self($course, $context, $user, $coursegroups, $groupids);
}
}

@ -1096,3 +1096,9 @@ function groups_sync_with_enrolment($enrolname, $courseid = 0, $gidfield = 'cust
return $affectedusers;
}
function core_group_inplace_editable($itemtype, $itemid, $newvalue) {
if ($itemtype === 'user_groups') {
return \core_group\output\user_groups_editable::update($itemid, $newvalue);
}
}

@ -56,6 +56,7 @@ $string['deletegroupsconfirm'] = 'Are you sure you want to delete the following
$string['deleteselectedgroup'] = 'Delete selected group';
$string['editgroupingsettings'] = 'Edit grouping settings';
$string['editgroupsettings'] = 'Edit group settings';
$string['editusersgroups'] = 'Edit users groups';
$string['enrolmentkey'] = 'Enrolment key';
$string['enrolmentkey_help'] = 'An enrolment key enables access to the course to be restricted to only those who know the key. If a group enrolment key is specified, then not only will entering that key let the user into the course, but it will also automatically make them a member of this group.

@ -28,8 +28,8 @@
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since 3.1
*/
define(['jquery', 'core/ajax', 'core/templates', 'core/notification', 'core/str', 'core/config', 'core/url'],
function($, ajax, templates, notification, str, cfg, url) {
define(['jquery', 'core/ajax', 'core/templates', 'core/notification', 'core/str', 'core/config', 'core/url', 'core/form-autocomplete'],
function($, ajax, templates, notification, str, cfg, url, autocomplete) {
$('body').on('click keypress', '[data-inplaceeditable] [data-inplaceeditablelink]', function(e) {
if (e.type === 'keypress' && e.keyCode !== 13) {
@ -176,6 +176,7 @@ define(['jquery', 'core/ajax', 'core/templates', 'core/notification', 'core/str'
.html(options[i].value));
}
inputelement.val(el.attr('data-value'));
el.html('')
.append(lbl)
.append(inputelement);
@ -199,6 +200,63 @@ define(['jquery', 'core/ajax', 'core/templates', 'core/notification', 'core/str'
});
};
var turnEditingOnAutocomplete = function(el, args) {
var i,
inputelement = $('<select></select>').
attr('id', uniqueId('id_inplacevalue_', 20)).
addClass('custom-select'),
lbl = $('<label class="accesshide">' + mainelement.attr('data-editlabel') + '</label>')
.attr('for', inputelement.attr('id')),
options = args.options,
attributes = args.attributes,
saveelement = $('<a href="#"></a>');
for (i in options) {
inputelement
.append($('<option>')
.attr('value', options[i].key)
.html(options[i].value));
}
if (attributes.multiple) {
inputelement.attr('multiple', 'true');
}
inputelement.val(JSON.parse(el.attr('data-value')));
str.get_string('savechanges', 'core').then(function(s) {
return templates.renderPix('e/save', 'core', s);
}).then(function(html) {
saveelement.append(html);
return;
}).fail(notification.exception);
el.html('')
.append(lbl)
.append(inputelement)
.append(saveelement);
inputelement.focus();
inputelement.select();
autocomplete.enhance(inputelement,
attributes.tags,
attributes.ajax,
attributes.placeholder,
attributes.caseSensitive,
attributes.showSuggestions,
attributes.noSelectionString);
inputelement.on('keyup', function(e) {
if ((e.type === 'keyup' && e.keyCode === 27) || e.type === 'focusout') {
// We need 'keyup' event for Escape because keypress does not work with Escape.
turnEditingOff(el);
}
});
saveelement.on('click', function(e) {
var val = JSON.stringify(inputelement.val());
turnEditingOff(el);
updateValue(el, val);
});
};
var turnEditingOn = function(el) {
el.addClass('inplaceeditingon');
el.attr('data-oldcontent', el.html());
@ -210,6 +268,8 @@ define(['jquery', 'core/ajax', 'core/templates', 'core/notification', 'core/str'
turnEditingOnToggle(el, options);
} else if (type === 'select') {
turnEditingOnSelect(el, $.parseJSON(options));
} else if (type === 'autocomplete') {
turnEditingOnAutocomplete(el, $.parseJSON(options));
} else {
turnEditingOnText(el);
}

@ -193,6 +193,27 @@ class inplace_editable implements templatable, renderable {
return $this;
}
/**
* Sets the element type to be an autocomplete field
*
* @param array $options associative array with dropdown options
* @param array $attributes associative array with attributes for autoselect field. @see AMD module core/form-autocomplete
* @return self
*/
public function set_type_autocomplete($options, $attributes) {
$this->type = 'autocomplete';
$pairedoptions = [];
foreach ($options as $key => $value) {
$pairedoptions[] = [
'key' => $key,
'value' => $value,
];
}
$this->options = json_encode(['options' => $pairedoptions, 'attributes' => $attributes]);
return $this;
}
/**
* Whether the link should contain all of the content or not.
*/

@ -442,7 +442,7 @@ class core_external extends external_api {
array(
'component' => new external_value(PARAM_COMPONENT, 'component responsible for the update', VALUE_REQUIRED),
'itemtype' => new external_value(PARAM_NOTAGS, 'type of the updated item inside the component', VALUE_REQUIRED),
'itemid' => new external_value(PARAM_INT, 'identifier of the updated item', VALUE_REQUIRED),
'itemid' => new external_value(PARAM_RAW, 'identifier of the updated item', VALUE_REQUIRED),
'value' => new external_value(PARAM_RAW, 'new value', VALUE_REQUIRED),
));
}

@ -194,9 +194,11 @@ function groups_get_grouping($groupingid, $fields='*', $strictness=IGNORE_MISSIN
* @param mixed $userid optional user id or array of ids, returns only groups of the user.
* @param int $groupingid optional returns only groups in the specified grouping.
* @param string $fields
* @param bool $withmembers If true - this will return an extra field which is the list of userids that
* are members of this group.
* @return array Returns an array of the group objects (userid field returned if array in $userid)
*/
function groups_get_all_groups($courseid, $userid=0, $groupingid=0, $fields='g.*') {
function groups_get_all_groups($courseid, $userid=0, $groupingid=0, $fields='g.*', $withmembers=false) {
global $DB;
// We need to check that we each field in the fields list belongs to the group table and that it has not being
@ -219,7 +221,7 @@ function groups_get_all_groups($courseid, $userid=0, $groupingid=0, $fields='g.*
}
}
if (empty($userid) && $knownfields) {
if (empty($userid) && $knownfields && !$withmembers) {
// We can use the cache.
$data = groups_get_course_data($courseid);
if (empty($groupingid)) {
@ -239,13 +241,13 @@ function groups_get_all_groups($courseid, $userid=0, $groupingid=0, $fields='g.*
// Yay! We could use the cache. One more query saved.
return $groups;
}
$memberselect = '';
$memberjoin = '';
if (empty($userid)) {
$userfrom = "";
$userwhere = "";
$params = array();
} else {
list($usql, $params) = $DB->get_in_or_equal($userid);
$userfrom = ", {groups_members} gm";
@ -261,12 +263,35 @@ function groups_get_all_groups($courseid, $userid=0, $groupingid=0, $fields='g.*
$groupingwhere = "";
}
if ($withmembers) {
$memberselect = 'ugm.id AS ugmid, ugm.userid, ';
$memberjoin = ' LEFT JOIN {groups_members} ugm ON ugm.groupid = g.id ';
}
array_unshift($params, $courseid);
return $DB->get_records_sql("SELECT $fields
FROM {groups} g $userfrom $groupingfrom
$results = $DB->get_records_sql("SELECT $memberselect $fields
FROM {groups} g $userfrom $groupingfrom $memberjoin
WHERE g.courseid = ? $userwhere $groupingwhere
ORDER BY name ASC", $params);
if ($withmembers) {
// We need to post-process the results back into standard format.
$groups = [];
foreach ($results as $row) {
if (!isset($groups[$row->id])) {
$row->members = [$row->userid => $row->userid];
unset($row->userid);
unset($row->ugmid);
$groups[$row->id] = $row;
} else {
$groups[$row->id]->members[$row->userid] = $row->userid;
}
}
$results = $groups;
}
return $results;
}

@ -294,9 +294,10 @@ fieldset.coursesearchbox label {
outline: none;
}
/** Undo some bootstrap things */
.form-autocomplete-selection + .form-control {
.form-autocomplete-selection + input.form-control {
width: auto;
display: inline-block;
vertical-align: middle;
}
.form-autocomplete-selection [data-active-selection=true] {

@ -75,11 +75,26 @@ class participants_table extends \table_sql {
*/
protected $countries;
/**
* @var stdClass[] The list of groups with membership info for the course.
*/
protected $groups;
/**
* @var string[] Extra fields to display.
*/
protected $extrafields;
/**
* @var stdClass The course details.
*/
protected $course;
/**
* @var context The course context.
*/
protected $context;
/**
* Sets up the table.
*
@ -98,7 +113,9 @@ class participants_table extends \table_sql {
parent::__construct('user-index-participants-' . $courseid);
// Get the context.
$this->course = get_course($courseid);
$context = \context_course::instance($courseid, MUST_EXIST);
$this->context = $context;
// Define the headers and columns.
$headers = [];
@ -118,6 +135,12 @@ class participants_table extends \table_sql {
$columns[] = $field;
}
// Load and cache the course groupinfo.
$this->groups = groups_get_all_groups($courseid, 0, 0, 'g.*', true);
// Add column for groups.
$headers[] = get_string('groups');
$columns[] = 'groups';
// Get the list of fields we have to hide.
$hiddenfields = array();
if (!has_capability('moodle/course:viewhiddenuserfields', $context)) {
@ -187,6 +210,25 @@ class participants_table extends \table_sql {
return $OUTPUT->user_picture($data, array('size' => 35, 'courseid' => $this->courseid)) . ' ' . fullname($data);
}
/**
* Generate the groups column.
*
* @param \stdClass $row
* @return string
*/
public function col_groups($user) {
global $OUTPUT;
$usergroups = [];
foreach ($this->groups as $coursegroup) {
if (isset($coursegroup->members[$user->id])) {
$usergroups[] = $coursegroup->id;
}
}
$editable = new \core_group\output\user_groups_editable($this->course, $this->context, $user, $this->groups, $usergroups);
return $OUTPUT->render_from_template('core/inplace_editable', $editable->export_for_template($OUTPUT));
}
/**
* Generate the city column.
*