2

Passing string of sobject name via trigger on ...how to fetch the sobject name of type sobject in class..

class
{
method(String operationType,list <Sobject> ,list<sobject>,string objecttype)
{
  //operation type means insert or update or delete
//objecttype means 'customobj__c'
Sobject obj;
}
}

I want to utilise objecttype to get sobject in obj

Or any help in getting the sobject?

2

You shouldn't be passing strings around whenever there's a better data type available. It's very easy to have undetected typos in strings that can cause failures that are hard to find. Instead, you should be using tokens and enums whenever possible. Here's how I used to write a trigger handler:

public class TriggerHandler {
    public enum Op { XINSERT, XUPDATE, XDELETE, XUNDELETE };
    public static void handle(Op operation, Map<Id, SObject> oldVal, SObject[] newVal) {
        SObjectType triggerObject = newVal == null? oldVal.getSObjectType(): newVal.getSObjectType();
        // Do whatever you need here
    }
}

As you can see, I don't use any string values at all. There's no chance for a typo. If I need to check the type, I can do this:

if(triggerObject == Lead.SObjectType) {
    // ...

If I have a typo, like OpportunityLinItem, it won't compile. If I'm using a string, it will compile, but will have a fatal error later that can be hard to track down. Note that I do the same thing to denote the trigger operation-- I use an enum, so I can't possibly have a typo.

Imagine if you're using String op and you accidentally type in if(op == 'insret') { ..., you might wonder why your logic isn't working as intended until you find the offending line. If the class is a few thousands of lines long, you're in for a long night and lots of coffee. Then, you have your unit tests, where you might need to use strings again. Double your chances for mysteriously failing unit tests.

I've got a better method for trigger handlers than described here, but hopefully I've convinced you to stop using strings when you can, and prefer the use of enums and/or tokens, as appropriate. They are there to help you avoid mistakes in your code, and you should use them as such.

1

Try something like this:

public myControllerExtension(ApexPages.StandardController stdController) {
    String type = stdController.getRecord().getSObjectType().getDescribe().getName();
}

You can take help from the below link: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dynamic_describe_objects_understanding.htm

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.