You need to sign in to do that
Don't have an account?
contentdocument trigger with query no results
Hello, im trying to write this trigger for ContentDocuments on Cases
but it seems when i try to locate the Content im not getting any results for my query.
FATAL_ERROR|System.QueryException: List has no rows for assignment to SObject
What am i doing wrong here??
trigger JiraAttachmentTrigger on ContentDocument (after insert, after update) {
// create a set of all the account ids for SOQL below
Set<id> caseIds = new Set<id>();
for (ContentDocument c : Trigger.new)
caseIds.add(c.Id);
for (ContentDocument att:Trigger.new)
{
String id = att.id;
String parentObjId = att.ParentId;
// create a map so that the account is locatable by its Id
Map<id, Case> caseMap = new Map<id, Case>(
[Select id, Jira_Key__c FROM Case WHERE Id = :parentObjId LIMIT 1]);
//Map<id, ContentVersion> cv = new Map<id, ContentVersion>(
//[SELECT id,VersionData,ContentDocumentId FROM ContentVersion WHERE ContentDocumentId = :id AND IsLatest = true LIMIT 1]);
ContentVersion cv = [SELECT id,VersionData FROM ContentVersion WHERE ContentDocumentId = :id AND IsLatest = true LIMIT 1];
String key = caseMap.Get(parentObjId).Jira_Key__c;
String file_name = att.title;
Blob file_body = cv.VersionData;
System.debug('Size of upload file: ' + att.ContentSize);
JiraAttachment.uploadFile(file_body, file_name, key);
}
}
You need to read about trigger bulkification:
1. Never ever write a SOQL query inside any “for” loop. If you do that, your trigger is guaranteed to hit the governor limits.
2. Never ever perform a DML operation inside a “for” loop.
3. Do not fetch unnecessary data. Only fetch those fields and objects in your SOQL that you really require.
4. Always try to separate trigger and it's handler class.
5. In your code try to put null check conditions at every place where the record has the possibility to come null or undefined.
Follow this link also:
http://www.sfdc99.com/2014/01/18/bulkifying-code/
Try this code and change add conditions according to your requirement:
trigger JiraAttachmentTrigger on ContentDocument (after insert, after update) {
Set<id> caseIds = new Set<id>();
Set<id> parentIds = new Set<id>();
for (ContentDocument c : Trigger.new) {
caseIds.add(c.Id);
parentIds.add(c.ParentId);
}
Map<id, Case> caseMap = new Map<id, Case>(
[Select id, Jira_Key__c FROM Case WHERE Id IN : parentIds LIMIT 1]);
Map<id, ContentVersion> cv = new Map<id, ContentVersion>(
[SELECT id,VersionData,ContentDocumentId FROM ContentVersion WHERE ContentDocumentId IN : caseIds AND IsLatest = true LIMIT 1]);
}
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi
Thanks for the help with the coding.
However, i know that i may not follow best pracitices for this, my main question is still how do i get the Content Body so i can send the body?
How should the handler class look?