function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ExploreForceExploreForce 

Apex:CONSTRUCTOR.Pls help

If i have two VF pages,
<apex:page standardController="Request__c" extensions="LocationRequestController" sidebar="false"> and
AND

<apex:page standardController="Order" extensions="LocationRequestController" sidebar="false">.

Controller:

public LocationRequestController(ApexPages.StandardController controller) {
       
        AccId= ApexPages.currentPage().getParameters().get('AccId');
   if(object==Request__c)
        {
        system.debug('AccId'+ AccId);
        ReqUser=(Request__c) controller.getRecord();
        ReqUser.Location__c=AccId;
        brequest=true;
       
        }
        else
        {
         OrderReq=(Order) controller.getRecord();
         OrderReq.AccountId=AccId;
         blorder=true;
        }
}
Is this allowed in salesforce?
IS there any way i can differentiate, based on object?
ExploreForceExploreForce
System.TypeException: Invalid conversion from runtime type SOBJECT:Order to SOBJECT:Request__c
Rahul SharmaRahul Sharma
Hi,

Use Id methods to find the token of the object.
public LocationRequestController(ApexPages.StandardController controller) {
    
    // validate the id before assignment, following line will throw an exception if id is not valid   
    Id accId= ApexPages.currentPage().getParameters().get('AccId');
    
    // Use Id method for determining the token/api name of object
    Schema.SObjectType objectToken = accId.getSObjectType();
    
    if(objectToken == Request__c.sObjectType)
    {
        system.debug('AccId'+ AccId);
        ReqUser=(Request__c) controller.getRecord();
        ReqUser.Location__c=AccId;
        brequest=true;
    }
    else if(objectToken == Order.sObjectType) {
        OrderReq=(Order) controller.getRecord();
        OrderReq.AccountId=AccId;
        blorder=true;
    } else {
        // throw error or handle for other objects
    }
}
Hope it helps! :)

ExploreForceExploreForce
one more Solution:

try{
            ReqUser=(Request__c) controller.getRecord();
           
            }
           catch(System.TypeException e){
                  OrderReq=(Order) controller.getRecord();
                
     }
Rahul SharmaRahul Sharma
Yes, but it won't work when you would want to use this class as an extension, for another standard object ;)