Search code examples
javascriptalfresco

Can't move node to its own tree using Alfresco's Javascript API


I've just written a script using the Javascript API so I can use it as a Rule to a Space. Whenever a document enters in a space, it basically checks document's name to get the parent directory it will be stored in (document's name contains parent's folder name), then creates future parent directory (if it doesn't exist), and finally moves the document into it.

I'm having troubles with this last step. Whenever I try to move the document into the recently created folder, I get the following error:

Node has been pasted into its own tree.

This is my code so far, which I think is pretty much auto-descriptive:

var fileName= document.properties.name;
var fields = fileName.split('.');

var parentName= fields[0];
var newNode=space.childByNamePath(parentName);

if (newNode === null) { //create folder and move document into it

  newNode=space.createFolder(parentName);  //works
  document.move(newNode); //I'm getting the error here

}else{ //folder already exists, just move document into it

    document.move(newNode); //here too

}

If I comment out the document.move(newNode); lines everything else works fine. Parent folder is successfully created but obviously the document keeps stored at the root of the current space, which is not what I need. Indeed I need to move it into the actual folder.

Am I doing something wrong? Any help would be much appreciated. Thanks.

UPDATE: Indeed I found out that the move() call inside the if scope it's working if I comment out the other call inside the else scope. So the error is being thrown at the else move() call. Also if I remove the else clause and put just one move() call after if scope, it also produces the same error.


Solution

  • You should run your rule as a background process, it will solve the problem ("Run rule in background" option).