This is strange - or not as Richtext is a son of a b**ch in general. I want to track if a document (resp. the richtext items) have attachments or not to set other fields in my backend document. I created a static Java method to compute the stuff. The method is called from the postSaveDocument event of my datasource. This is the method:
/**
* Set flag fields if attachments exist or not
*
* @param xspdoc
*/
public static void setAttachments(final Document doc, final boolean post) {
try {
if (doc.hasItem("audioFile")) {
doc.replaceItemValue("audioHasFile", "1");
} else {
doc.removeItem("audioHasFile");
}
if (doc.hasItem("audioCase")) {
doc.replaceItemValue("audioHasCase", "1");
} else {
doc.removeItem("audioHasCase");
}
if (doc.hasItem("audioTrackliste")) {
doc.replaceItemValue("audioHasTrackliste", "1");
} else {
doc.removeItem("audioHasTrackliste");
}
if (post)
doc.save();
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is: everytime I add an attachment to one of the RTF items on my Xpage (via Fileupload control), save the document with the simple action, the item e.g. "audioHasFile" is set to "1". Bene!
If I then reopen the document, delete the attachment (via the Filedownload control trashicon) and save the document again, the backend doesn't recognize that the attachment has gone and the item e.g. "audioHasFile" is not removed but still holds the value "1" which was set before.
Only if a re-open the document in my Xpage (from a View panel) and save it again, the field is removed as the backend now recognizes that there is no attachment.
I know what you are thinking: the lack of an attachment doesn't mean that theres is no item for it - wrong! I also tried to check the type of the Richtext item via getType == 1 (Item.ATTACHMENT) - no luck.
Info: I deliver the Document parameter via currentDocument.getDocument(true) - so I am dealing with the synchronized backend document here.
To be clear: it's not a question of testing in general but a problem of timing.
Any idea how to solve this? Thank you in advance! :)
UPDATE: This is the solution that works:
/**
* Set flag fields if attachments exist or not
*
* @param xspdoc
*/
public static void setAttachments(final DominoDocument doc) {
try {
doc.replaceItemValue("audioHasFile", doc.getAttachmentList("audioFile").size() > 0 ? "1" : "");
doc.replaceItemValue("audioHasTrackliste", doc.getAttachmentList("audioTrackliste").size() > 0 ? "1" : "");
doc.replaceItemValue("audioHasCase", doc.getAttachmentList("audioCase").size() > 0 ? "1" : "");
// key
doc.replaceItemValue("audioKey", doc.getItemValueString("audioTitle").toLowerCase().replaceAll("\\s+",""));
doc.save();
} catch (Exception e) {
e.printStackTrace();
}
}