Add To Watchlist Macro

Last modified by Thomas Mortagne on 2026/02/26 15:43

cogIllustrates how to programmatically add documents to user watchlists
TypeDoc (Velocity Macro)
Category
Developed by

Eugen Colesnicov

Rating
0 Votes
LicenseGNU Lesser General Public License 2.1

Table of contents

Description

Normally, you can only add documents to the watchlist of the current user, using:

$xwiki.watchlist.addDocument($doc.fullName)

But sometimes you'd like to add documents to the watchlist of another user. This velocity macro shows how to do it. For example, place this code inside a page calling "Macro.AddToAnyUserWatchlist"

{{velocity}}
#macro(addToAnyUserWatchlist $user $item)
  #set($itemdoc=$xwiki.getDocument($item))
  #set($userdoc=$xwiki.getDocument($user))
  #set($witem = $itemdoc.getWiki()+":"+$itemdoc.getFullName())
  #set($obj=$userdoc.getObject("XWiki.WatchListClass"))
  #set($wdocs=$obj.getProperty('documents').getValue())
  #if($wdocs.indexOf($witem)==-1)
    #set($wdocs=$wdocs+","+$witem)
    $obj.set('documents',$wdocs)
    $userdoc.save()
  #end
#end
{{/velocity}}

Example of calling this velocity macro from another page:

{{velocity}}
{{include document="Macro.AddToAnyUserWatchlist"/}}
#addToAnyUserWatchlist("XWiki.TestUser", "Sandbox.TestPage3")
{{/velocity}}
Information

You can use this strategy to insert any object to watch to user watchlists and not just documents. For example you can could add 'wikis', 'spaces' and 'users'.

Get Connected