Setting user roles when creating a user via script

You’re close. Due to technical limitations, some things get accessed differently than others. Here’s the sample script I gave to training:

def printResponse(responseList):
    if len(responseList) > 0:
        for response in responseList:
            print "", response
    else:
        print " None" 

# Make a brand new 'blank' user. Not saved until we, well, save
username = event.source.parent.getComponent('Text Field').text
user = system.user.getNewUser("", "myAwesomeUser")

# Let's fill in some fields. Note we have two ways to access property names
user.set("firstname", "Naomi")
user.set(user.LastName, "Nagata")
user.set("password", "1234567890")

# We can add contact info one at a time. Up to the script user to make sure the type is legit
user.addContactInfo("email", "naomi@roci.com")

#we can add a lot of contact info
contactInfo = {"email":"ignition_user@mycompany.com","sms": "5551212"}
user.addContactInfo(contactInfo)

# We can delete contact info. Only deletes if both fields match.
user.removeContactInfo("sms", "5551212")

# we can add a role. If the role doesn't already exist, user save will fail, depending on user source
user.addRole("mechanic")

# we can add a lot of roles
roles = ["Administrator", "prisoner"] 
user.addRoles(roles)

# and we can remove a role
user.removeRole("prisoner")

# we can add a schedule adjustment too
date2 = system.date.now()
date1 = system.date.midnight(date2)
user.addScheduleAdjustment(date1, date2, False, "An adjustment note")

# we can make a bunch of adjustments and add them en-masse
date3 = system.date.addDays(date2, -4)
adj1 = system.user.createScheduleAdjustment(date3, date2, True, "Another note")
adj2 = system.user.createScheduleAdjustment(date3, date1, False, "")
user.addScheduleAdjustments([adj1, adj2])

# and we can remove a schedule adjustment. All fields must match.
user.removeScheduleAdjustment(date1, date2, True, "Some other note")

# finally need to save our new user and print responses
response = system.user.addUser("", user)

warnings = response.getWarns()
print "Warnings are:"
printResponse(warnings)
 
errors = response.getErrors()
print "Errors are:"
printResponse(errors)
 
infos = response.getInfos()
print "Infos are:"
printResponse(infos)```
2 Likes