The official developer documentation is at: Developer guide | Alfresco Documentation
JavaScript APICookbook
This page is the central page for examples for the JavaScript API. Feel free to add your examples to this.
Example scripts can be found in the Company Home/Data Dictionary/Scripts folder in a default Alfresco installation.
Creates a backup of a document as it is added to a space:
// find the backup folder - create if not already exists
var backupFolder = space.childByNamePath('Backup');
if (backupFolder == null && space.hasPermission('CreateChildren'))
{
// create the folder for the first time
backupFolder = space.createFolder('Backup');
}
if (backupFolder != null && backupFolder.hasPermission('CreateChildren'))
{
// copy the doc into the backup folder
var copy = document.copy(backupFolder);
if (copy != null)
{
// change the name so we know it's a backup
copy.name = 'Backup of ' + copy.name;
copy.save();
}
}
Creates a backup of a document and logs the doc properties to a log text file:
// find the backup folder - create if not already exists
var backupFolder = space.childByNamePath('Backup');
if (backupFolder == null && space.hasPermission('CreateChildren'))
{
// create the folder for the first time
backupFolder = space.createFolder('Backup');
}
if (backupFolder != null && backupFolder.hasPermission('CreateChildren'))
{
// copy the doc into the backup folder
var copy = document.copy(backupFolder);
if (copy != null)
{
// change the name so we know it's a backup
var backupName = 'Backup of ' + copy.name;
copy.name = backupName;
copy.save();
}
// record the time of the backup to a log file
var logFile = backupFolder.childByNamePath('backuplog.txt');
if (logFile == null)
{
logFile = backupFolder.createFile('backuplog.txt');
}
if (logFile != null)
{
logFile.content += 'File: ' + backupName +
'\tDate: ' + new Date().toUTCString() +
'\tSize: ' + copy.size + '\r\n';
}
}
Appends a copyright line of content to plain text and HTML files:
if (document.hasPermission('Write'))
{
if (document.mimetype == 'text/plain')
{
document.content += '\r\n\r\nCopyright (C) 2006';
}
else if (document.mimetype == 'text/html')
{
document.content += '
Copyright © 2006';
}
}
Adding several aspects to a document:
var props = new Array(1);
props['cm:template'] = document.nodeRef;
document.addAspect('cm:templatable', props);
props = new Array(1);
props['cm:lockIsDeep'] = true;
document.addAspect('cm:lockable', props);
props = new Array(1);
props['cm:hits'] = 1;
document.addAspect('cm:countable', props);
Finds all the documents containing the text 'Alfresco' using a Lucene search and records the results to a log file:
// log the docs that currently contain the word 'Alfresco' to a log file
var logFile = userhome.childByNamePath('alf docs.txt');
if (logFile == null)
{
logFile = userhome.createFile('alf docs.txt');
}
if (logFile != null)
{
// execute a lucene search across the repo for the text 'alfresco'
var docs = search.luceneSearch('TEXT:alfresco');
var log = '';
for (var i=0; i
Returning a result value. This is useful for scripts that are processed using URLs via the Script Command Servlet, as the results are returned as the HTML response from the servlet:
function result()
{
return 'The name of my home space is: ' + userhome.name;
}
result();
The following solution will also return a value if placed at the end of a script:
// script here
// ...
var result = 'some results...';
result;
Creates a document, makes it versionable, checks it out, modifies the content of the working copy, checks it in again and then repeats the process but checks in the document with a version history note and as a major version increment:
// create file, make it versionable
var doc = userhome.createFile('checkmeout.txt');
doc.addAspect('cm:versionable');
doc.content = 'original text';
// check it out and update content on the working copy
var workingCopy = doc.checkout();
workingCopy.content = 'updated text 1';
// check it in
doc = workingCopy.checkin();
// check it out again
workingCopy = doc.checkout();
workingCopy.content = 'updated text 2';
// check it in again, but with a version history note and as major version increment
doc = workingCopy.checkin('a history note', true);
Changes the mimetype of a document after setting the content:
var file = userhome.createFile('testfile.html');
file.content = 'some HTML here';
file.mimetype = 'text/html';
Creates document content and converts it to new formats using the transformation API:
// create a plain text doc and convert to PDF, generated file will be placed in same space as original
var doc1 = userhome.createFile('transform_me1.txt');
doc1.mimetype = 'text/plain';
doc1.content = 'This is plain text';
var trans1 = doc1.transformDocument('application/pdf');
// create an HTML doc and convert to plain text, generated file will be created under the companyhome space
var doc2 = userhome.createFile('transform_me2.html');
doc2.mimetype = 'text/html';
doc2.content = 'This is an HTML document!';
var trans2 = doc2.transformDocument('text/plain', companyhome);
// create an HTML doc and convert to flash swf file, generated file will be created under the companyhome space
var doc3 = userhome.createFile('transform_me3.html');
doc3.mimetype = 'text/html';
doc3.content = 'This is an HTML document!';
var trans3 = doc3.transformDocument('application/x-shockwave-flash', companyhome);
Converts an image document to other formats:
// convert an image document to GIF format and place it in company home
var gifImage = document.transformImage('image/gif', companyhome);
// convert an image to JPG format and resize to thumbnail image
var thumbImage = document.transformImage('image/jpeg', '-resize 120');
Resize image (update image document):
//create a temporary folder to store the resized image (same name as original document)
var transformedImagesFolder = space.createFolder('_temp_resize_folder_' + _document.name);
//create a new resized image
var transformedImage = document.transformImage('image/jpeg', '-resize 1024x768', transformedImagesFolder);
//update the original image content with the resized image
document.properties.content.write(transformedImage.properties.content);
//delete the temporary resized image + folder
transformedImage.remove();
transformedImagesFolder.remove();
Executes a template from the repository against the current Document node:
var template = companyhome.childByNamePath('/Data Dictionary/Presentation Templates/doc_info.ftl');
if (template != null)
{
var result = document.processTemplate(template);
// output result to the console - could just as easily save the content into a new node...
logger.log(result);
}
Builds a FreeMarker template directly in the script, also builds up an argument list for the template. The result of the template is saved to a new node as the content:
var template = '
' +
'The ID argument: ${args['id']}';
var args = new Array()
args['id'] = '01234-56789';
var result = document.processTemplate(template, args);
// save the template result content to a new node in my home space
var outputFile = userhome.createFile('output.txt');
outputFile.content = result;
var permissions = userhome.permissions;
var result = '';
for (var i=0; i
';
}
result;
<import resource='classpath:alfresco/extension/myutils.js'>
<import resource='/Company Home/Data Dictionary/Scripts/mylib.js'>
// your script here
// ...
var node1 = userhome.createNode('create test1.txt', 'cm:content');
node1.content = 'node1 content';
var node2 = userhome.createNode(null, 'sys:base');
var props = new Array();
props['cm:name'] = 'create test3.txt';
var node3 = userhome.createNode(null, 'cm:content', props);
props['cm:name'] = 'node name4.txt';
props['cm:title'] = 'node title4';
var node4 = userhome.createNode(null, 'cm:content', props, 'cm:contains');
var result = 'nodes created ok';
result;
// example iterating array indexes using 'for .. in'
var out1 = '';
for (i in userhome.children)
{
out1 += userhome.children[i].name + '
';
}
// example iterating array values using 'for each .. in'
var out2 = '';
for each (n in userhome.children)
{
out2 += n.name + '
';
}
var out = out1 + '
' + out2;
out;
Another example of iterating nodes can be found in Iterate_Nodes.
Example of creating and removing target assocations:
var sourceNode = userhome.createNode('testassocsfile.txt', 'cm:content');
sourceNode.content = 'the original text';
sourceNode.addAspect('cm:transformable');
var destNode = userhome.createNode('translation1.txt', 'cm:content');
destNode.content = 'the translation of the original text';
sourceNode.createAssociation(destNode, 'cm:formats');
var tempNode = userhome.createNode('dummy.txt', 'cm:content');
tempNode.content = 'dummy';
sourceNode.createAssociation(tempNode, 'cm:formats');
// get the nodes at the end of the 'cm:formats' association
var translations = sourceNode.assocs['cm:formats'];
sourceNode.removeAssociation(tempNode, 'cm:formats');
tempNode.remove();
{{AVMWarning}}
Example using the AVM API to process a webproject store - the store name is passed as store on the url arguments:
if (args['store'] == null)
{
logger.log('ERROR: 'store' argument not specified.');
}
else
{
main();
}
function main()
{
var storeRootNode = avm.lookupStoreRoot(args['store']);
if (storeRootNode != null)
{
var path = storeRootNode.path + '/ROOT/admin/index.html';
var node = avm.lookupNode(path);
if (node == null)
{
return 'ERROR: unable to find path: ' + path;
}
var store = avm.lookupStore(args['store']);
if (store == null)
{
return 'ERROR: unable to lookup store: ' + args['store'];
}
var rootNode = store.lookupRoot();
if (rootNode == null)
{
return 'ERROR: unable to find root node for store: ' + store.name;
}
var out = '';
var results = store.luceneSearch('TEXT:tomcat');
for (var i=0; i
';
}
return out;
}
}
function result()
{
return (actions.registered);
}
result();
Output will be something like:
[transform-image, mail, copy-to-web-project, extract-metadata, counter, check-in, simple-workflow, script, transform, remove-features, specialise-type, import, add-features, link-category, blog-post, move, copy, check-out]
You can use the E4X module of Javascript to parse XML.
var store = avm.lookupStore('test');
var results = store.luceneSearch('wca\\:parentformname:Press Release');
var pressreleases = new XML();
pressreleases = <pressreleases></pressreleases>
for (var i=0, len=results.length; i
You can then return the XML using this:
${pressreleases}
IMPORTANT NOTE:
When using in a workflow definition XML, a Javascript '//' comment style stops following code from executing as linebreaks are removed before processing. Use the '/* ... */' comment format instead.
Also, the '
/* Javascript E4X module has problems with XML header */
if ( str.substr(0,5).indexOf('<?xml') != -1 ) {
positionRootElement = str.indexOf('<', 5);
str = str.substr( positionRootElement, str.length - 1 );
}
One of the ways to escape '
bpm_package.children[0].content = '
So, all the text containing '
org.mozilla.javascript.EvaluatorException: missing ; before statement (AlfrescoJS#1)
var futureDate = new Date();
futureDate.setDate(futureDate.getDate() + 7);
var currentDate = new Date();
var testList = companyhome.childByNamePath('Sites/sitenamegoeshere/dataLists/b2c74e68-1ccf-494e-83a6-b36049d2607a');
// note: no error checking, or seeing if dataLists or this particular datalist even exists
var testEntry = testList.createNode(null, 'dl:task');
testEntry.properties['cm:title'] = document.name;
testEntry.properties['cm:description'] = document.name;
testEntry.properties['dl:ganttStartDate'] = currentDate;
testEntry.properties['dl:ganttEndDate'] = futureDate;
testEntry.properties['dl:taskPriority'] = 'High';
testEntry.properties['dl:taskStatus'] = 'Not Started';
testEntry.save();
testEntry.createAssociation(people.getPerson('assigneeusername'),'dl:taskAssignee');