Best way to programmatically set User timezone preference

Hi,

I’d like to update a User’s Timezone preference from within an extension. The newer xwiki-platform-user-api doesn’t have methods for setting that property. I can see from the OIDC extension it gets an XWikiDocument for the User, and from that the XObject (BaseObject), referencing a BaseClass obtained from calling xcontext.getWiki().getUserClass(xcontext);. A timezone field can then be set on the BaseObject.

Is that still the best/latest way to set/get the timezone preference for a user or is there an alternative?

Thanks in advance,
Alex

Hello,

I don’t think there’s an alternative right now, we started to build a User API (see: https://extensions.xwiki.org/xwiki/bin/view/Extension/User%20Module/API/) but it doesn’t contain much so far, still IMO it’s something that should go in there in the future.

Thanks @surli. As I used the xwiki-platform-user-api (User API and you mention) in other places, I did look there first but as you say, setting the timezone preference isn’t covered by that API.

In case it’s useful for other people (and hopefully someone can validate what I’m doing), my code is currently doing the following:

... other code ...
private void updateTimezone(String timezone) {
    var userXWikiDocument = getUserXWikiDocument(context, wikiId, userInfo.getId());
    var userObject = getUserObject(context, userXWikiDocument);
    var currentTz = userObject.getStringValue("timezone");

    if (!timezone.equals(currentTz)) {
        userObject.set("timezone", timezone, context);
        logger.trace("Setting user timezone preference to [{}]", timezone);
        context.getWiki().saveDocument(userXWikiDocument, "Update user timezone", context);
    }
}

private XWikiDocument getUserXWikiDocument(XWikiContext context, String wikiName, String userId) throws XWikiException {
    var spaceReference = new SpaceReference(wikiName, "XWiki");
    var userDocRef = new DocumentReference(userId, spaceReference);
    return context.getWiki().getDocument(userDocRef, context);
}
    
private BaseObject getUserObject(XWikiContext context, XWikiDocument userXWikiDoc) throws XWikiException {
    BaseClass userClass = context.getWiki().getUserClass(context);
    BaseObject userObject = userXWikiDoc.getXObject(userClass.getDocumentReference(), true, context);
    return userObject;
}
1 Like

I’m going to mark my post as the solution as it is working for me and nobody has said that what I’ve done is wrong or could be better :slight_smile:

1 Like