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
KasiWKasiW 

Opportunity Refresh into View mode after save

hello, I have a VF page "Renew" button similar to standard clone button. It allows the user to perform what I call "quick edits" for a few key fields. When the opportunity  is opened by using Renawal button , the opportunity fields are displayed  in edit mode. If the users changes or adds to these fields, then clicks save, it does save the record as I want it to. However, instead of refreshing to display the VF page, the newly created (renewed) opportunity in View mode,  it refreshes to display the page layout of the Renewed (first) oportunity in Edit Mode. 

How can I see the new Renewed Opportunity in View Mode? Here  is my code. Please help. I appriciate any feedback.


public class OpportunityRenewalController
{

    private ApexPages.StandardController controller {get; set;}
    private Opportunity opp {get;set;}
    public ID newRecordId {get;set;}

    public OpportunityRenewalController(ApexPages.StandardController controller)
        {
            this.controller = controller;
            opp = (Opportunity)controller.getRecord();
        }
    
    public PageReference RenewalWithItems()
    {
        Savepoint sp = Database.setSavepoint();
        Opportunity newOpp;
         
        try
        {
            opp = [SELECT Id, AccountId, Account.Name, Name, Contract_Type__c, StageName, MarketRegion__c, Service_Offering__c, Market__c, Forecast_Status__c,Sub_Practice__c,CurrencyIsoCode, Billing_Type__c, Service_Line__c, CampaignId, Campaign.Name, Amount, Notice_Period__c, Delivery_Location__c, LeadSource, NextStep, Description, Insurance_Coverage__c, Unusual_Insurance_Requirements__c, Warranty_Clause__c, Unusual_Damages__c, Risk_Do_Dont__c, Unusual_Risk__c, External_Counsel__c, Payment_Terms__c, Gross_Margin__c, Authorized_Approver__c, Risk_Assessment_Comment__c, Contract_Start_Date__c, Contract_End_Date__c, Contract_Duration__c, CIBER_Opportunity_ID__c, Nearshore__c, Offshore__c, Onshore__c,Delivery_Location_Type_Poland_GSC__c,Solution_Set__c FROM Opportunity
                WHERE Id = :opp.Id];
            if (opp.StageName != 'Pre-Qualified')
            {
                 
                opp.StageName = 'Qualified';
                opp.Forecast_Status__c = 'Probable';                
                opp.Booking_Type__c = 'Existing Client - Renewals/Extension';                
                if ((opp.Contract_Start_Date__c != Null) &&  (opp.Contract_End_Date__c != Null))
                                {
                    opp.Contract_Start_Date__c = opp.Contract_End_Date__c.addDays(1);
                    integer iDuration = integer.valueOf(opp.Contract_Duration__c);
                    opp.Contract_End_Date__c = opp.Contract_Start_Date__c.addMonths(iDuration)-1;
                    opp.CloseDate = opp.Contract_Start_Date__c;
                    opp.Number_of_Positions__c =opp.Number_of_Positions__c=5;
                    opp.Probability = 75;                   
                                       
                }
                       
           
                else
                {
                    opp.CloseDate = Date.today().addMonths(1);
                    opp.Contract_Start_Date__c = Null;
                    opp.Contract_End_Date__c = Null;
                    integer iDuration = 0; 
                    opp.Probability = 75;                 
                }
                    
                     
                newOpp = opp.Clone(false);
                insert newOpp;
                     
                newRecordId = newOpp.id;
                     
                List<OpportunityLineItem> items = new List<OpportunityLineItem>();
                for (OpportunityLineItem li : [Select l.Id, l.Quantity, l.Description, l.ServiceDate,l.UnitPrice, l.CurrencyIsoCode, l.PricebookEntryId, l.SortOrder, l.Cost_Price__c From OpportunityLineItem l where OpportunityId = :opp.id])
                {
                OpportunityLineItem newLI = li.clone(false);
                newLI.OpportunityId = newOpp.id;
                items.add(newLI);
                }
                insert items;
                     
                Note myNote = new Note (ParentId = newRecordId, Title = 'This is the renewal of CIBER Opportunity ID ' + opp.CIBER_Opportunity_ID__c);
                insert myNote;
            }
            else
            {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Renewal not possible for opportunities with phase line Pre-Qualified'));
                return null;
            }
        }                            
            catch (Exception e)
            {
            Database.rollback(sp);
            ApexPages.addMessages(e);
            return null;
            }
  
           //return new ApexPages.StandardController(newOpp).edit();
           //PageReference oppPage = new ApexPages.standardcontroller(newOpp).view();
        PageReference oppPage = new ApexPages.StandardController(newOpp).edit();
        //PageReference oppPage = new PageReference('/' + newOpp.id+'/e');
        //oppPage.setRedirect(true);


            //oppPage = new ApexPages.standardcontroller(newOpp).view();
            oppPage.setRedirect(true);
            return oppPage;
    }
}
Amit Chaudhary 8Amit Chaudhary 8
Please try below code:-

return new PageReference ('/'+newOpp.id);

Please let us know if this will help you
Susan JohnsonSusan Johnson
Hi Amit,

I tried this and it does not work.  It no longer opens the opportunity page in edit mode.
Amit Chaudhary 8Amit Chaudhary 8
Please try below code:-
public class OpportunityRenewalController
{
    private ApexPages.StandardController controller {get; set;}
    private Opportunity opp {get;set;}
    public ID newRecordId {get;set;}

    public OpportunityRenewalController(ApexPages.StandardController controller)
        {
            this.controller = controller;
            opp = (Opportunity)controller.getRecord();
        }
    
    public PageReference RenewalWithItems()
    {
        Savepoint sp = Database.setSavepoint();
        Opportunity newOpp;
        try
        {
            opp = [SELECT Id, AccountId, Account.Name, Name, Contract_Type__c, StageName, MarketRegion__c, Service_Offering__c, Market__c, Forecast_Status__c,Sub_Practice__c,CurrencyIsoCode, Billing_Type__c, Service_Line__c, CampaignId, Campaign.Name, Amount, Notice_Period__c, Delivery_Location__c, LeadSource, NextStep, Description, Insurance_Coverage__c, Unusual_Insurance_Requirements__c, Warranty_Clause__c, Unusual_Damages__c, Risk_Do_Dont__c, Unusual_Risk__c, External_Counsel__c, Payment_Terms__c, Gross_Margin__c, Authorized_Approver__c, Risk_Assessment_Comment__c, Contract_Start_Date__c, Contract_End_Date__c, Contract_Duration__c, CIBER_Opportunity_ID__c, Nearshore__c, Offshore__c, Onshore__c,Delivery_Location_Type_Poland_GSC__c,Solution_Set__c FROM Opportunity
                WHERE Id = :opp.Id];
            if (opp.StageName != 'Pre-Qualified')
            {
                opp.StageName = 'Qualified';
                opp.Forecast_Status__c = 'Probable';                
                opp.Booking_Type__c = 'Existing Client - Renewals/Extension';                
                if ((opp.Contract_Start_Date__c != Null) &&  (opp.Contract_End_Date__c != Null))
                                {
                    opp.Contract_Start_Date__c = opp.Contract_End_Date__c.addDays(1);
                    integer iDuration = integer.valueOf(opp.Contract_Duration__c);
                    opp.Contract_End_Date__c = opp.Contract_Start_Date__c.addMonths(iDuration)-1;
                    opp.CloseDate = opp.Contract_Start_Date__c;
                    opp.Number_of_Positions__c =opp.Number_of_Positions__c=5;
                    opp.Probability = 75;                   
                                       
                }
                       
           
                else
                {
                    opp.CloseDate = Date.today().addMonths(1);
                    opp.Contract_Start_Date__c = Null;
                    opp.Contract_End_Date__c = Null;
                    integer iDuration = 0; 
                    opp.Probability = 75;                 
                }
                    
                     
                newOpp = opp.Clone(false);
                insert newOpp;
                     
                newRecordId = newOpp.id;
                     
                List<OpportunityLineItem> items = new List<OpportunityLineItem>();
                for (OpportunityLineItem li : [Select l.Id, l.Quantity, l.Description, l.ServiceDate,l.UnitPrice, l.CurrencyIsoCode, l.PricebookEntryId, l.SortOrder, l.Cost_Price__c From OpportunityLineItem l where OpportunityId = :opp.id])
                {
                OpportunityLineItem newLI = li.clone(false);
                newLI.OpportunityId = newOpp.id;
                items.add(newLI);
                }
                insert items;
                     
                Note myNote = new Note (ParentId = newRecordId, Title = 'This is the renewal of CIBER Opportunity ID ' + opp.CIBER_Opportunity_ID__c);
                insert myNote;
            }
            else
            {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Renewal not possible for opportunities with phase line Pre-Qualified'));
                return null;
            }
        }                            
            catch (Exception e)
            {
				Database.rollback(sp);
				ApexPages.addMessages(e);
				return null;
            }
  
			if(newOpp != null)
			{
				return new PageReference ('/'+newOpp.id);
            }
			else
			{
				return null;
			}
    }
}

If your override the clone button. Then please try to create new button and open your VF page

Please let us know if this will help you

 
Susan JohnsonSusan Johnson
Sorry - no difference, it still does not open in Edit mode.
Amit Chaudhary 8Amit Chaudhary 8
Please try below code:-

 
public class OpportunityRenewalController
{
    private ApexPages.StandardController controller {get; set;}
    private Opportunity opp {get;set;}
    public ID newRecordId {get;set;}

    public OpportunityRenewalController(ApexPages.StandardController controller)
        {
            this.controller = controller;
            opp = (Opportunity)controller.getRecord();
        }
    
    public PageReference RenewalWithItems()
    {
        Savepoint sp = Database.setSavepoint();
        Opportunity newOpp;
        try
        {
            opp = [SELECT Id, AccountId, Account.Name, Name, Contract_Type__c, StageName, MarketRegion__c, Service_Offering__c, Market__c, Forecast_Status__c,Sub_Practice__c,CurrencyIsoCode, Billing_Type__c, Service_Line__c, CampaignId, Campaign.Name, Amount, Notice_Period__c, Delivery_Location__c, LeadSource, NextStep, Description, Insurance_Coverage__c, Unusual_Insurance_Requirements__c, Warranty_Clause__c, Unusual_Damages__c, Risk_Do_Dont__c, Unusual_Risk__c, External_Counsel__c, Payment_Terms__c, Gross_Margin__c, Authorized_Approver__c, Risk_Assessment_Comment__c, Contract_Start_Date__c, Contract_End_Date__c, Contract_Duration__c, CIBER_Opportunity_ID__c, Nearshore__c, Offshore__c, Onshore__c,Delivery_Location_Type_Poland_GSC__c,Solution_Set__c FROM Opportunity
                WHERE Id = :opp.Id];
            if (opp.StageName != 'Pre-Qualified')
            {
                opp.StageName = 'Qualified';
                opp.Forecast_Status__c = 'Probable';                
                opp.Booking_Type__c = 'Existing Client - Renewals/Extension';                
                if ((opp.Contract_Start_Date__c != Null) &&  (opp.Contract_End_Date__c != Null))
                                {
                    opp.Contract_Start_Date__c = opp.Contract_End_Date__c.addDays(1);
                    integer iDuration = integer.valueOf(opp.Contract_Duration__c);
                    opp.Contract_End_Date__c = opp.Contract_Start_Date__c.addMonths(iDuration)-1;
                    opp.CloseDate = opp.Contract_Start_Date__c;
                    opp.Number_of_Positions__c =opp.Number_of_Positions__c=5;
                    opp.Probability = 75;                   
                                       
                }
                       
           
                else
                {
                    opp.CloseDate = Date.today().addMonths(1);
                    opp.Contract_Start_Date__c = Null;
                    opp.Contract_End_Date__c = Null;
                    integer iDuration = 0; 
                    opp.Probability = 75;                 
                }
                    
                     
                newOpp = opp.Clone(false);
                insert newOpp;
                     
                newRecordId = newOpp.id;
                     
                List<OpportunityLineItem> items = new List<OpportunityLineItem>();
                for (OpportunityLineItem li : [Select l.Id, l.Quantity, l.Description, l.ServiceDate,l.UnitPrice, l.CurrencyIsoCode, l.PricebookEntryId, l.SortOrder, l.Cost_Price__c From OpportunityLineItem l where OpportunityId = :opp.id])
                {
                OpportunityLineItem newLI = li.clone(false);
                newLI.OpportunityId = newOpp.id;
                items.add(newLI);
                }
                insert items;
                     
                Note myNote = new Note (ParentId = newRecordId, Title = 'This is the renewal of CIBER Opportunity ID ' + opp.CIBER_Opportunity_ID__c);
                insert myNote;
            }
            else
            {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Renewal not possible for opportunities with phase line Pre-Qualified'));
                return null;
            }
        }                            
            catch (Exception e)
            {
				Database.rollback(sp);
				ApexPages.addMessages(e);
				return null;
            }
  
			if(newOpp != null)
			{
				return new PageReference ('/'+newOpp.id+'/e?retURL=%2F'+newOpp.id);
            }
			else
			{
				return null;
			}
    }
}


                return new PageReference ('/'+newOpp.id+'/e?retURL=%2F'+newOpp.id);


 
Susan JohnsonSusan Johnson
That's it!!  You did it!!!  Thanks so much, I really appreciate your help.
Amit Chaudhary 8Amit Chaudhary 8
Dont forget to mark best solution. So that if anyone has this issue this post can help
KasiWKasiW
Hi Amit, My collogue and I did not test this enough and said too early that the code was working. It looks like this is still not working for us. We realized that the record has been saved by the time it is opened in edit mode. Any suggestions?
 
Amit Chaudhary 8Amit Chaudhary 8
According to above code. After click on save (RenewalWithItems) button your record will saved and will still open in Edit Mode.
Can you please confirm you want to open new record in edit mode or view mode ?

If you to open new record in edit mode then please try below code :-
   return new PageReference ('/'+newOpp.id+'/e?retURL=%2F'+newOpp.id);

If you to open your record in View mode then please try below code:-
   return new PageReference ('/'+newOpp.id);

Thanks
Amit Chaudhary
KasiWKasiW
Hi Amit, thank you for your promt reply. Here is what happens: 1. user clicks Renewal button on opportunity, 2. the renewed opportunity is created bahind the scene (we don't what this to happen because we dont give users ability to enter additional fields). 3.
 right away new record is opened in edit mode (which is ok) but when user, by any chance, clicks Cancel button, the new records is already saved without the needed fields populated.  Is it possible to have the new record in edit mode without saving?  I appriciate your help. Best
Amit Chaudhary 8Amit Chaudhary 8
Hi KasiW,

I have create one demo page for you according to your requirement. Please create one button and attched below code with your button.

PAGE:-
<apex:page standardController="Opportunity" extensions="OppCloneExtension">
    <apex:form >
        <apex:pageBlock >
                <apex:pageblockSection >
                        <apex:inputField value="{!opp.Name}"/>
                        <apex:inputField value="{!opp.StageName }"/>
                        <apex:inputField value="{!opp.Accountid}"/>
                        <apex:inputField value="{!opp.Amount}"/>
                        <apex:inputField value="{!opp.CloseDate}"/>
                </apex:pageblockSection>
                <apex:pageblockButtons >
                        <apex:commandButton action="{!RenewalWithItems}" value="RenewalWithItems"/>
                
                </apex:pageblockButtons>
        
        </apex:pageBlock>    
    
    
    </apex:form>
</apex:page>
Class:-
public with sharing class OppCloneExtension {

public Opportunity Opp {get;set;}
public Opportunity newOpp {get;set;}
public ID newRecordId {get;set;}

    public OppCloneExtension(ApexPages.StandardController controller) {
             opp = (Opportunity)controller.getRecord();
             opp = [select id,name,AccountID,Account.Name ,CloseDate,Amount,StageName from Opportunity where id =:opp.id ]   ; 
    }

    public PageReference RenewalWithItems()
    {
                newOpp = opp.Clone(false);
                insert newOpp;
                             
                newRecordId = newOpp.id;
                     
                List<OpportunityLineItem> items = new List<OpportunityLineItem>();
                for (OpportunityLineItem li : [Select l.Id, l.Quantity, l.Description, l.ServiceDate,l.UnitPrice,  l.PricebookEntryId, l.SortOrder From OpportunityLineItem l where OpportunityId = :opp.id])
                {
                    OpportunityLineItem newLI = li.clone(false);
                    newLI.OpportunityId = newOpp.id;
                    items.add(newLI);
                }
                
                insert items;


        return new PageReference('/'+newOpp .id);
    }
}
Amit Chaudhary 8Amit Chaudhary 8
Your class should be like below :-
 
public class OpportunityRenewalController
{
    private ApexPages.StandardController controller {get; set;}
    private Opportunity opp {get;set;}
    public ID newRecordId {get;set;}

		public OpportunityRenewalController(ApexPages.StandardController controller)
        {
            this.controller = controller;
            opp = (Opportunity)controller.getRecord();
			
        }
	
	public PageReference OnLoadTest()
	{
				opp = [SELECT Id, AccountId, Account.Name, Name, Contract_Type__c, StageName, MarketRegion__c, Service_Offering__c, Market__c, Forecast_Status__c,Sub_Practice__c,CurrencyIsoCode, Billing_Type__c, Service_Line__c, CampaignId, Campaign.Name, Amount, Notice_Period__c, Delivery_Location__c, LeadSource, NextStep, Description, Insurance_Coverage__c, Unusual_Insurance_Requirements__c, Warranty_Clause__c, Unusual_Damages__c, Risk_Do_Dont__c, Unusual_Risk__c, External_Counsel__c, Payment_Terms__c, Gross_Margin__c, Authorized_Approver__c, Risk_Assessment_Comment__c, Contract_Start_Date__c, Contract_End_Date__c, Contract_Duration__c, CIBER_Opportunity_ID__c, Nearshore__c, Offshore__c, Onshore__c,Delivery_Location_Type_Poland_GSC__c,Solution_Set__c FROM Opportunity
                WHERE Id = :opp.Id];
				
            if (opp.StageName != 'Pre-Qualified')
            {
                opp.StageName = 'Qualified';
                opp.Forecast_Status__c = 'Probable';                
                opp.Booking_Type__c = 'Existing Client - Renewals/Extension';                
                if ((opp.Contract_Start_Date__c != Null) &&  (opp.Contract_End_Date__c != Null))
                {
                    opp.Contract_Start_Date__c = opp.Contract_End_Date__c.addDays(1);
                    integer iDuration = integer.valueOf(opp.Contract_Duration__c);
                    opp.Contract_End_Date__c = opp.Contract_Start_Date__c.addMonths(iDuration)-1;
                    opp.CloseDate = opp.Contract_Start_Date__c;
                    opp.Number_of_Positions__c =opp.Number_of_Positions__c=5;
                    opp.Probability = 75;                   
                                       
                }
                else
                {
                    opp.CloseDate = Date.today().addMonths(1);
                    opp.Contract_Start_Date__c = Null;
                    opp.Contract_End_Date__c = Null;
                    integer iDuration = 0; 
                    opp.Probability = 75;                 
                }
			}
            else
            {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Renewal not possible for opportunities with phase line Pre-Qualified'));
                return null;
            }
	}
	
		
    public PageReference RenewalWithItems()
    {
        Savepoint sp = Database.setSavepoint();
        Opportunity newOpp;
        try
        {
                newOpp = opp.Clone(false);
                insert newOpp;

                newRecordId = newOpp.id;
                     
                List<OpportunityLineItem> items = new List<OpportunityLineItem>();
                for (OpportunityLineItem li : [Select l.Id, l.Quantity, l.Description, l.ServiceDate,l.UnitPrice, l.CurrencyIsoCode, l.PricebookEntryId, l.SortOrder, l.Cost_Price__c From OpportunityLineItem l where OpportunityId = :opp.id])
                {
					OpportunityLineItem newLI = li.clone(false);
					newLI.OpportunityId = newOpp.id;
					items.add(newLI);
                }
                insert items;

                Note myNote = new Note (ParentId = newRecordId, Title = 'This is the renewal of CIBER Opportunity ID ' + opp.CIBER_Opportunity_ID__c);
                insert myNote;
        }                            
            catch (Exception e)
            {
				Database.rollback(sp);
				ApexPages.addMessages(e);
				return null;
            }
			if(newOpp != null)
			{
				return new PageReference ('/'+newOpp.id);
            }
			else
			{
				return null;
			}
    }
}

Page should be like below :-
<apex:page standardController="Opportunity" extensions="OppCloneExtension" action="{!OnLoadTest}">
    <apex:form >
        <apex:pageBlock >
            <apex:pageMessages ></apex:pageMessages>
                <apex:pageblockSection >
                        <apex:inputField value="{!opp.Name}"/>
                        <apex:inputField value="{!opp.StageName }"/>
                        <apex:inputField value="{!opp.Accountid}"/>
                        <apex:inputField value="{!opp.Amount}"/>
                        <apex:inputField value="{!opp.CloseDate}"/>
                </apex:pageblockSection>
                <apex:pageblockButtons >
                        <apex:commandButton action="{!RenewalWithItems}" value="RenewalWithItems"/>
                
                </apex:pageblockButtons>
        
        </apex:pageBlock>    
    
    
    </apex:form>
</apex:page>

Please let us know if this will help you.

Thank
Amit Chaudhary
amit.salesforce21@gmail.com