trigger CreateTask on ContentVersion (after insert) 
List<Task> insertTask = new List<Task>();
Task newTask = new Task();
Schema.DescribeSObjectResult k=Contact.sObjectType.getDescribe();
Id Contactapi = k.getKeyPrefix();
for(ContentVersion newCase : Trigger.new)
//Assign Content Version values to Task
if (Contactapi.getSobjectType() == Contact.SObjectType)
     newTask.WhoId =  newCase.FirstPublishLocationId; 
      newTask.WhatId = newCase.FirstPublishLocationId; 

This is what I try to create a task when document upload in Contact, Account, and Custom Objects. I need to check whether the object is contact or else to assign WhoId.


You don't need the Describe API. Just use the Id class's methods. Adapted from the documentation:

Contact a = new Contact(LastName = 'Test');
insert a;
Id myId = a.id;
System.assertEquals(Contact.SObjectType, myId.getSobjectType());

That's suitable for situations where you only have an Id value, such as working with polymorphic relationships - although you can also manage this in SOQL by filtering on the Type field across the relationship, e.g.,

SELECT Subject FROM Task WHERE Who.Type = 'Contact'

If you have not an Id but an sObject instance of unknown type, you can similarly ask it for getSobjectType(), or use an Apex switch on construct to handle multiple types cleanly.

This code is tautological - it compares a value to itself.

Schema.DescribeSObjectResult k=Contact.sObjectType.getDescribe();
      String Contactapi = k.getKeyPrefix();
    if(Contactapi == '003') 

If you have a contact Id in a variable myId, you can ask if that Id represents a Contact with

if (myId.getSobjectType() == Contact.SObjectType)

Salesforce uses SmartIds, which means the first three prefix will be same across all orgs for few standard objects.

For contact its 003,

Here is the full list

  • This does not extend to custom objects where a different ID prefix can be assigned for the same object on different orgs.
    – Phil W
    Dec 13 '20 at 11:35

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.