Working with Document Events - Kentico 8.2

Kyle G asked on April 7, 2015 19:04

I want to have a "HasAttachments" field on my form that updates to true/false if the document has attachments. I am looking to do exactly what @davey_lad did in #2 in the last post here. It's too bad he didn't post the code:

http://devnet.kentico.com/forums/f65/fp30/t38826/determine-if-smart-search-result-has-%28or-is%29-an

I've tried many different events, but the closest I've come to is using the Insert_Before and Update_Before. This requires the document to be saved twice in order for it to update to the correct value.

if (doc.Attachments.Count > 0) { doc.SetValue("HasAttachments", true); } else { doc.SetValue("HasAttachments", false); }

It looks like attachments don't go into the CMS_Attachment table until the document is Published. A simple save doesn't do it. So, I'm looking to tie into the event where it adds to the CMS_Attachment table.

I've used quite a few from this list, to no avail:

https://docs.kentico.com/display/K8/Reference+-+Global+system+events

Recent Answers


Brenden Kehren answered on April 7, 2015 19:19

So the Document attachments save and delete events of a Document don't work for what you need? Check out that last link you posted and search the page for "SaveAttachment". I'd think on that event you can capture what you need and update the node referenced with the attachment.

0 votesVote for this answer Mark as a Correct answer

Kyle G answered on April 7, 2015 19:32

I tried SaveAttachment and DeleteAttachment After events and they didn't do anything. They didn't even update the value after 2 saves, like Insert/Update Before.

Here's my code:

private void SaveAttachment_After(object sender, DocumentEventArgs e)
{
var doc = e.Node;

if (doc.Attachments.Count > 0) { doc.SetValue("HasAttachments", true); }
else { doc.SetValue("HasAttachments", false); }
}
}

0 votesVote for this answer Mark as a Correct answer

Brenden Kehren answered on April 7, 2015 21:15

Your initial post stated you noticed it didn't save anything to the attachments table until the document was published. Did you see if your code was fired when the document was published? Is your event initialized properly?

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.