I'm trying to get a page to redirect to a custom object that is being created in the below class but it's not doing it at the moment.

Can I call this class from a trigger and get the page to redirect?

public class CAWarrantyToMaintenance {

public static PageReference createMaint(id oldId){
    Maintenance_Contract__c oldmc =[select id, End_Date_Editable__c from Maintenance_Contract__c where id =:oldId];
    Maintenance_Contract__c newmc = new Maintenance_Contract__c();
    newmc.Contract_Type__c = 'MCD';
    newmc.New_Contract__c = oldmc.id;
    newmc.Start_Date__c = oldmc.End_Date_Editable__c;
    insert newmc; 

    PageReference maintPage = new PageReference ('https://cs80.salesforce.com/' + newmc.id);
    return maintPage;

No, you can't redirect from a trigger. You'd have to create a Visualforce page to call the code and then perform your redirect. Also, you should always use StandardController to redirect:

return new ApexPages.StandardController(newmc).view();
  • 1
    huh, never crossed my mind that there might be a way to redirect to an sObject detail page without some form of url-hacking. – Derek F Feb 28 '17 at 20:21
  • 1
    @DerekF It's apparently one of the best kept secrets. I've never seen anyone other than myself use it :p – sfdcfox Feb 28 '17 at 20:58

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.