2

Forgive me but I'm a bit of a newb when it comes to Apex and found below that was written by a previous developer who worked for my company. Handler creates a task after user inserts an attachment. Works fine but throws an error on Milestone PM+ Projects as it seems that tasks are not supported.

My question is-is it possible to update this code to basically say if objType=Project do nothing else proceed to create task? Any support would be greatly appreciated.

/*
* \arg ModifiedBy       : 
* \arg Description      : Handler class to create task after attchment is inserted
*/
public with sharing class AttachmentHandler 
{
    /* Start - Constructor */
    public AttachmentHandler() 
    {
        //do nothing
    }
    /* End - Constructor */

    /**
    @MethodName : onAfterUpdate
    @Param      : 
    @Description: 
    **/
    public void onAfterInsert(List<Attachment> lstAttach)
    {
        String userId = UserInfo.getUserId();
        List<Task> lstTask = new List<Task>();
        for(Attachment objAttach : lstAttach)
        {
            Schema.SObjectType objType = objAttach.parentId.getSobjectType();
            String strObjType = objType+'';
            if( strObjType != 'Task') 
            {
            Task objTask = new Task();
            objTask.Subject = 'Upload attachment - '+objAttach.Name;
            objTask.Priority = 'Normal';
            objTask.Type = 'File Attachment';
            objTask.Status = 'Completed';
            objTask.ActivityDate = objAttach.CreatedDate.Date();
            objTask.Task_Completion_Date__c = objAttach.CreatedDate;
            if(strObjType == 'Contact' || strObjType == 'Lead')
            objTask.WhoId = objAttach.parentId;
            else
            objTask.WhatId = objAttach.parentId;
            objTask.OwnerId = userId;

            lstTask.add(objTask);

            }
        }

        if(!lstTask.isEmpty())
            insert lstTask;
    }
}
  • Before others attempt to format your code, could you please format it so others can focus helping with actual problem your facing? – jagmohan Aug 17 '17 at 4:56
  • You need to modify line 27 to if( strObjType != 'Task' && strObjType != 'Project__c'(API Name of Project Object)) , this condition will not allow to create task for both Project and Task object. – salesforce Developer Aug 17 '17 at 6:04
  • Matt-thanks for reformatting this into structured, clean code and my apologies for posting it in the format that I did. – toddk Aug 18 '17 at 8:19
  • Salesforce Developer-thanks for posting suggested modification to line 27. This is so simple and makes complete sense now. I feel like a dope for not having figured this one out before having posted it. Such an awesome site. Don't know what I would do if online sources like this didn't exist. Thanks again – toddk Aug 18 '17 at 8:20
2

The code is already doing something similar for Task:

    if (strObjType != 'Task') 
    {

so the basic change would be (you will have to look in the Setup UI to discover the API name of the problem object including its namespace prefix):

    if (strObjType != 'Task' && strObjType != 'xyz__Project__c') 
    {

But a cleaner way to do this would be:

// Declare at class level
private static final Set<SObjectType> EXCLUSIONS = new Set<SObjectType>{
    Task.SObjectType,
    xyz__Project__c.SObjectType
};

    // In the onAfterInsert method
    SObjectType objType = objAttach.parentId.getSobjectType();
    if (!EXCLUSIONS.contains(objType))
    {

Using the SObjectType values directly allows the Apex compiler to check that the tokens are correct.

You could also reverse the logic here and nominate INCLUSIONS instead.

-1

Try this, it will help you.

public void onAfterInsert(List lstAttach) { 
String userId = UserInfo.getUserId(); 
List lstTask = new List();
for(Attachment objAttach : lstAttach) { 
 Schema.SObjectType objType = objAttach.parentId.getSobjectType(); 

 String parentRecId = objAttach.parentId;
 String objectAPIName = '';
 String keyPrefix = recordId.substring(0,3);
 for( Schema.SObjectType obj : Schema.getGlobalDescribe().Values() ){
     String prefix = obj.getDescribe().getKeyPrefix();
     if(prefix == keyPrefix){
         objectAPIName = obj.getDescribe().getName();
         break;
     }
 }

 if(objectAPIName != 'Project__c(object API Name)'){
     String strObjType = objType+'';
     if( strObjType != 'Task') {
     Task objTask = new Task();
     objTask.Subject = 'Upload attachment - '+objAttach.Name; 
     objTask.Priority = 'Normal'; 
     objTask.Type = 'File Attachment'; 
     objTask.Status = 'Completed';
     objTask.ActivityDate = objAttach.CreatedDate.Date();
     objTask.Task_Completion_Date__c = objAttach.CreatedDate; 
     if(strObjType == 'Contact' || strObjType == 'Lead') 
       objTask.WhoId = objAttach.parentId; 
     else objTask.WhatId = objAttach.parentId; 
       objTask.OwnerId = userId;

     lstTask.add(objTask);
    }
 }
}
if(!lstTask.isEmpty())
  insert lstTask;
}
  • Doing a global describe within a for loop is not good idea. In this case, we can avoid the use of global describe. Or, if it is really needed to do a describe call, it's better to cache the results of describe call in a Map and reference that for future iterations. – jagmohan Aug 17 '17 at 6:31
  • Code dumps with no explanation aren't very useful answers. They tend to generate a series of comments about "it doesn't work" followed by "try this instead", which are hard to follow. They also aren't very helpful to other people who may visit this question with similar problems in the future. Explaining what your code is doing, and why it works makes an answer more useful. Doing so gives people an idea of what's wrong/missing from their own code, making it possible for people to attempt their own fixes if the answer isn't 100% correct and broadening the situations the answer can handle – Derek F Aug 17 '17 at 13:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.