How can I assign “coursecreator” role to a user in moodle?

Tags: php moodle
By : Pk19000
Source: Stackoverflow.com
Question!

I write a plugin in moodle that should assign "coursecreator" role to some users.

$coursecreatorroleid = $DB->get_field('role', 'id', array('shortname' => 'coursecreator'));

role_assign($coursecreatorroleid, $user->id,context_course::instance());

if (user_has_role_assignment($user->id, $coursecreatorroleid))
    echo "True";

But it does't work. Can anybody help me please? Thanks.

By : Pk19000


Answers

You can't create a course context instance, without giving a course id.

So, you should write:

$context = context_course::instance($courseid);
role_assign($coursecreatorroleid, $user->id, $context); 

Alternatively, if you want to assign the role at the site level, or at a category level (which makes sense for the course creator role), you should use context_system::instance() or context_coursecat::instance($catid).

If also advise you to turn on debugging (if not already on) - http://docs.moodle.org/en/Debugging - as that will give you helpful error messages and warnings.

By : davosmith


I suppose this would help

s = { "A":1, "B":1,  "C":1, "D":0, "E":2, "F":0 }
rez = sorted(s.items(), key = lambda x: (x[1],x[0]))

Result is

[('D', 0), ('F', 0), ('A', 1), ('B', 1), ('C', 1), ('E', 2)]

If you need a reversed order, just use -x[1] instead of x[1]



C++11 solution:

#include <type_traits>

template<typename From, typename To>
To map(From e) {
    return static_cast<To>(
        static_cast<typename std::underlying_type<To>::type>(
        static_cast<typename std::underlying_type<From>::type>(e)));
}

This casting cascade is very explicit and supports enum classes.

For older C++ versions and for enums without class, static_cast<Enum2>(e) would suffice.

Edit:

With template specialization, you can use map without specifying any types explicitly:

enum class Enum1: int {A, B, C, D};
enum class Enum2: char {A1, B1, C1, D1};

template<typename T>
struct target_enum {
};

template<>
struct target_enum<Enum1> {
    typedef Enum2 type;
};

template<typename From>
typename target_enum<From>::type map(From e) {
    typedef typename target_enum<From>::type To;
    return static_cast<To>(
        static_cast<typename std::underlying_type<To>::type>(
        static_cast<typename std::underlying_type<From>::type>(e)));
}

You can then call map(Enum1::A). Also works with simple, non-class enums.

By : flyx


This video can help you solving your question :)
By: admin