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
Sudhir_MeruSudhir_Meru 

Page Redirect is not working

Hi,

  I created a page redirect inside controller. Below highlited is the code to call page redirect. I am redirect the page to opporunity after data is saved. 
  
 Please suggest me how to modify its not working

// Store Selected Records to Object/Table
public void processSelected() {
    Integer currentPageNumber = setCon.getPageNumber();
    selectedAssets = new List<Asset>();
    list<Temp_Assets__c> TempAssetList = new list<Temp_Assets__c>(); 
       
     
     setCon.setpageNumber(1);
    

while(true){
    List<Asset>  TempAssetLists = (List<Asset>)setCon.getRecords();
    for(Asset assetIns : TempAssetLists  ) {
          if(this.selectedContactIds.contains(assetIns.Id)){
             selectedAssets.add(assetIns);
            
            
           }
     }
if(setCon.getHasNext()){
  setCon.next();
  }
  else{
  break;
  }
  

        /**********Added by Unnat*********************************/
        //below code should only execute if Expiry term has a value
        Date maxDate=Date.valueOf('2000-1-1');
        Date minDate;
       
        //Calculate the maximum Date off of the selected dates
     
        //finds the latest expiry date out of the selected assets
        for (Asset assets: selectedAssets) {
            if(assets.Service_End_Date_Max__c > maxDate) {
                maxDate=assets.Service_End_Date_Max__c;
            }
        }
        System.debug('== Latest Service end Date is:'+ maxDate);
        minDate = maxDate;
        for (Asset assets: selectedAssets) {
            if(minDate > assets.Service_End_Date_Max__c) {
                minDate=assets.Service_End_Date_Max__c;
            }
        }
        System.debug('== Least Service end Date is:'+ minDate);
       
         
        //Validations
        if ((selectedAssets.size() < 1 ) || (expireTerms == '0' && GetExpireDate.Expire_Date__c== null )|| (expireTerms != '0' && GetExpireDate.Expire_Date__c!= null ) || (GetDistributor.Primary_Distributor__c == null ) || (GetReseller.Primary_Reseller__c == null ) || (GetOpportunity.Opportunity__c==null && GetNewOpportunity.New_Opportunity__c== null ) || (GetOpportunity.Opportunity__c!=null && GetNewOpportunity.New_Opportunity__c!= null )|| (GetExpireDate.Expire_Date__c < maxDate )) {
        //Validates that atleast one of the assets is selected from the install base
        if(selectedAssets.size() < 1 ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please select atleast one Asset to renew from the Install Base.'));
        }
        //Validates that atleast one of the Expiry Dates needs to have a value
        if(expireTerms == '0' && GetExpireDate.Expire_Date__c== null ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please enter the Expiry Term or Expiry Date for the selected Assets.'));
        }
        //Valation that only of the Expirty Dates can have a value
        else if(expireTerms != '0' && GetExpireDate.Expire_Date__c!= null ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'You can enter a value either in Expiry Date or Expiry Term, but not in both.'));
        }
        //Validation that the Distributor Name is required
        if(GetDistributor.Primary_Distributor__c == null ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please enter a value in Distributor'));
        }
        //Validation that Reseller Name is required
        if(GetReseller.Primary_Reseller__c == null ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please enter a value in Reseller'));
        }
        //Validation that atleast one Opportunity needs to have a value
        if(GetOpportunity.Opportunity__c==null && GetNewOpportunity.New_Opportunity__c== null ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please enter a value in either of the Opportunity'));
        }
        //Validation that only one of the Opportunities can have a value
        else if(GetOpportunity.Opportunity__c!=null && GetNewOpportunity.New_Opportunity__c!= null ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'You can enter a value either in Opportunity or New Opportunity, but not in both.'));
        }
        //Validation that will check if the Expiry Date has value less than the selected Asset Service End Date
        if(GetExpireDate.Expire_Date__c < maxDate ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Expiry Date that you entered is lower than Service End Date of the Asset'));
        }
        }
        else {
        //below code should only execute if Expiry term has a value
        //Date maxDate=Date.valueOf('2000-1-1');
        //Calculate the maximum Date off of the selected dates
       
        if (ExpireTerms !=null) {
        System.debug('== Expire Terms has a value');
       
            //There will be another condition to add the expiry term to the latest expiry date
            //String a='1 Year';
            System.debug('== ExpireTerms is: '+ ExpireTerms);
            if (ExpireTerms=='1') {
                System.debug('== First if condition');
                maxDate=maxDate.addYears(1);
            }
            else if (ExpireTerms == '3') {
            System.debug('== Second if condition');
                maxDate=maxDate.addYears(3);
            }
            else if (ExpireTerms == '5') {
            System.debug('== third if condition');
                maxDate=maxDate.addYears(5);
            }
            else {
                maxDate= GetExpireDate.Expire_Date__c;
            }
        }
        else {
        System.debug('== Else condition');
            maxDate= GetExpireDate.Expire_Date__c;  
        }
        System.debug('== Max Date is: ' + maxDate);
        Integer totalDays = minDate.daysBetween(maxDate);
        System.debug('== Total days difference is: '+ totalDays);
        /****************Completed by Unnat*****************************/
       
        //checks if the Monthly Quote is going to be more than 36 months and Monthly Quote Checkbox is selected
        /*if (totalDays > 1080 && Monthly_Quote == true ) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Since the Renewals in Months is more than 3 years, please uncheck the Monthly Quote checkbox'));
        }
        else {*/       
            System.debug('=- after the if condition');          
            Account ResellerAct;
            Account DistributorAct; 
            Opportunity Oppt;          
                               
            for(Asset Act : selectedAssets)
            {              
                Temp_Assets__c TempAsset = new Temp_Assets__c();
                TempAsset.Name = 'Sudhir';
                TempAsset.AccountId__c = Act.AccountId;
                TempAsset.Product__c = Act.Product2Id;
                //Added by Unnat
                TempAsset.Product_lookup__c= Act.Product2Id;
                TempAsset.Asset_Id__c = Act.Id;
                TempAsset.Serial_Number__c = Act.SerialNumber;
                TempAsset.Last_Contract_Number__c = Act.last_contract_number__c;
                TempAsset.Service_Start_Date__c = Act.Service_Start_Date_Min__c;
               
                //TempAsset.Service_End_Date__c = Act.Service_End_Date_Max__c;
                /***************Added by Unnat********************************************/
                TempAsset.Opp_Close_Date__c = minDate;
                TempAsset.Monthly_Quote__c = Monthly_Quote;
                System.debug('=- Monthly Quote is: ' + monthly_Quote);
               
                if (Act.Service_End_Date_Max__c != null) {
                    TempAsset.Service_End_Date__c = Act.Service_End_Date_Max__c;
                }
                else {
                    TempAsset.Service_End_Date__c = Act.InstallDate;
                }
               
                TempAsset.Install_Date__c = Act.InstallDate; 
                System.debug ('==== Reseller id is: '+ GetReseller.Primary_Reseller__c);
                TempAsset.Reseller__c = GetReseller.Primary_Reseller__c;
                TempAsset.Distributor__c = GetDistributor.Primary_Distributor__c;
               
                /****************Commented by Unnat****************************************************************************
               
                If (GetReseller.AccountId <> NULL)
                {     
                ResellerAct = [ SELECT Id FROM Account WHERE ID = :GetReseller.Primary_Reseller__c Limit 1];
                TempAsset.Reseller__c = ResellerAct.Id;     
                 System.debug ('==== Reseller id 2 is: '+ ResellerAct.Id);       
                }
              
                If (GetDistributor.AccountId <> NULL )
                {
                DistributorAct = [ SELECT Id FROM Account WHERE ID = :GetDistributor.Primary_Distributor__c Limit 1];
                TempAsset.Distributor__c = DistributorAct.Id;
                }
               
                ****************Completed by Unnat *****************************************************************************/
                If ( GetOpportunity.Opportunity__c <> NULL )
                {
                Oppt = [SELECT Id FROM Opportunity WHERE ID = :GetOpportunity.Opportunity__c Limit 1];
                TempAsset.Existing_Opportunity__c = Oppt.Id;
                }               
                TempAsset.Incumbent_Reseller__c = IncumbentReseller;
                TempAsset.Education__c = Education;
                //TempAsset.Expiry_Date__c = GetExpireDate.Expire_Date__c;
                TempAsset.Expiry_Date__c= maxDate;
               
                TempAsset.New_Opportunity__c = GetNewOpportunity.New_Opportunity__c;
                TempAsset.Expiry_Term__c = ExpireTerms;
               
                /* Insert Bundel Checkbox Value */               
                if (this.selectedContactIds2.contains(Act.Id)){
                    bundsprt=true;
                }
                else {
                    bundsprt=false;
                }
               
               
                TempAsset.Bundle_Support__c = bundsprt;
                System.debug('== Bundle Value is: ' + bundsprt);
               
                             //Add the selected Assets to the List
                TempAssetList.add(TempAsset);
            }
               
            Insert TempAssetList;                           
           
           
       // } //end of if Condition for check of days more than 3 years
       }
        setCon.setpageNumber(currentPageNumber);
        Redirect();
    }
   
   public pagereference Redirect()
   {
     String optyURL2 = 'https://cs20.salesforce.com/006m0000002MqNf';
     PageReference pageref = new PageReference(optyURL2);   //<----- changed here
     pageref.setRedirect(true);  
     return pageref;
    }


Thanks
Sudhir

Best Answer chosen by Sudhir_Meru
Arunkumar RArunkumar R
Can you try like this,

public class demo
{

public string baseURL{get;set;}
Public String existingId{get;set;}

public static void processSelected()
{
// Your function

}
 public PageReference pageRefMethod() {

//call your action method
 processSelected();

existingId = '006m0000002MqNf';
baseUrl = URL.getSalesforceBaseUrl().toExternalForm()+'/';

  PageReference send = new PageReference(baseURL + existingId);
    send.setRedirect(true);
    return send;

    }

}


In your visualforce page,

<apex:commandButton value="SAve" action="{!pageRefMethod}"/>


All Answers

SFDC_DevloperSFDC_Devloper
Hi,

  Try below code..

public pagereference Redirect()
   {
     PageReference page= new PageReference(System.currentPageReference().getURL());
     page.setRedirect(true);  
     return page;
    }

   [If it helps, mark it as "Best Answer"] 


Thanks,
Rockzz
Sudhir_MeruSudhir_Meru

Hi Rockzz, 

  Thanks for your reply. I want to redirect to https://cs20.salesforce.com/006m0000002MqNf 

  I dont  see this in your code Please let me know

Thanks

Sudhir

praveen murugesanpraveen murugesan
Hi Sudhir,

Instead of this public pagereference Redirect()
   {
     String optyURL2 = 'https://cs20.salesforce.com/006m0000002MqNf';
     PageReference pageref = new PageReference(optyURL2);   //<----- changed here
     pageref.setRedirect(true); 
     return pageref;
    }

you can use this

public pagereference Redirect()
   {

     PageReference pageref = new PageReference('/006m0000002MqNf');   //instead of hardcoded id you can mention opp id by using query
     pageref.setRedirect(true); 
     return pageref;
    }

Hope this helps.

Thanks
SFDC_DevloperSFDC_Devloper
HI Sudhir,

     What this URL Contains :https://cs20.salesforce.com/006m0000002MqNf..Please provide some more Info...

Thanks
Arunkumar RArunkumar R
Hi Sudhir,

Can you try this below code, 

public string baseURL{get;set;}
Public ID existingId{get;set;}
existingId = '006m0000002MqNf';

baseUrl = URL.getSalesforceBaseUrl().toExternalForm()+'/';

public PageReference getBackToAddendum(){
   
    PageReference send = new PageReference(baseURL + existingId);
    send.setRedirect(true);
    return send;
   
}


Sudhir_MeruSudhir_Meru

Hi Arun, 

  I tried your method i am getting error Error: Compile Error: unexpected token: '='

 In this line 
existingId = '006m0000002MqNf';


Also Can i call getBackToAddendum()  Inside another funcation after insert operation is done. 

Thanks

Sudhir

Sudhir_MeruSudhir_Meru
Hi Praveen Murgesan,

  I added as mentioned below but it is not working Please suggest me how to modify 

public with sharing class CCW_ContactPaginationController {
 
  //URL Passing Parameters. 
  String PageContractId = ApexPages.currentPage().getParameters().get('ContractId');     
  String PageAccountId  = ApexPages.currentPage().getParameters().get('AccountId');   
 
  public Asset   GetAccount{get;set;}
  public Asset   GetContract{get;set;} 
  public Asset   GetExpireDate{get;set;}
  public Asset   GetReseller{get;set;}
  public Asset   GetDistributor{get;set;}
  public String  IncumbentReseller{get;set;}
  public String  Education{get;set;}
  public Asset   GetOpportunity{get;set;}
  public Asset   GetNewOpportunity{get;set;}
  public String  ExpireTerms{get;set;}
  public boolean bundsprt{get;set;}
  public boolean Monthly_Quote {get;set;}
  
  //Our collection to class/wrapper objects wrapAsset
  public List<CCWRowItem> wrapAssetList {get; set;}
  public List<Asset> selectedAssets{get;set;} 
   /*
    *   item in context from the page
    */
    public String contextItem{get;set;}
    public String contextItem2{get;set;}
 
 
    /*
    *   set controller
    */
    private ApexPages.StandardSetController setCon;
    
    
    /*
    *   the contact ids selected by the user
    */
    private Set<Id> selectedContactIds;
    private Set<Id> selectedContactIds2= new set<Id>();
    
    
    /*
    *   constructor
    */
    public CCW_ContactPaginationController ()
    {
      GetAccount = new Asset();    //Get Account Id from Page 
      GetContract = new Asset();   //Get Contract Name from Page   
      GetExpireDate = new Asset();   // Date Picker   
      GetReseller = new Asset(); 
      GetDistributor = new Asset();  
      GetOpportunity = new Asset();   // Get Opportunity Id 
      GetNewOpportunity = new Asset();  // Get New Opportunity Name    
      fetch_data();        
     }
    
       
   public void fetch_data ()
   {
       
        //init variable
        this.selectedContactIds= new Set<Id>();
        //gather data set        
      Try 
       {  
       if ( GetAccount.AccountId == NULL && GetContract.Name == NULL )   
        {   
         if ( PageAccountId != NULL && PageContractId == NULL )
         {
          this.setCon = new ApexPages.StandardSetController( [SELECT Id, AccountId,Product2Id,SerialNumber,last_contract_number__c,Service_Start_Date_Min__c, Service_End_Date_Max__c,InstallDate,Bundle_Support__c FROM Asset WHERE AccountId = :PageAccountId Order by Service_End_Date_Max__c Desc Limit 1000] );
         }
         else if ( PageAccountId == NULL && PageContractId != NULL )
         {
         Contract C;
         C = [SELECT Name FROM Contract WHERE Id = :PageContractId Limit 1]; 
         this.setCon = new ApexPages.StandardSetController( [SELECT Id, AccountId,Product2Id,SerialNumber,last_contract_number__c,Service_Start_Date_Min__c, Service_End_Date_Max__c,InstallDate,Bundle_Support__c FROM Asset WHERE last_contract_number__c = :C.Name Order by Service_End_Date_Max__c Desc Limit 1000] );
         }
         else 
         { 
         this.setCon = new ApexPages.StandardSetController( [SELECT Id, AccountId,Product2Id,SerialNumber,last_contract_number__c,Service_Start_Date_Min__c, Service_End_Date_Max__c,InstallDate,Bundle_Support__c FROM Asset WHERE AccountId = '0013000000DULXG' Order by Service_End_Date_Max__c Desc Limit 1000] );                                            
         }
        }
      else if ( GetAccount.AccountId != NULL && GetContract.Name == NULL )   
        {
         this.setCon = new ApexPages.StandardSetController( [SELECT Id, AccountId,Product2Id,SerialNumber,last_contract_number__c,Service_Start_Date_Min__c, Service_End_Date_Max__c,InstallDate,Bundle_Support__c FROM Asset WHERE AccountId = :GetAccount.AccountId Order by Service_End_Date_Max__c Desc Limit 1000] ); 
        } 
       else if ( GetAccount.AccountId == NULL && GetContract.Name != NULL )
        { 
        this.setCon = new ApexPages.StandardSetController( [SELECT Id, AccountId,Product2Id,SerialNumber,last_contract_number__c,Service_Start_Date_Min__c, Service_End_Date_Max__c,InstallDate,Bundle_Support__c FROM Asset WHERE last_contract_number__c  = :GetContract.Name Order by Service_End_Date_Max__c Desc Limit 1000] );
        } 
       else if ( GetAccount.AccountId != NULL && GetContract.Name != NULL ) 
        {
        this.setCon = new ApexPages.StandardSetController( [SELECT Id, AccountId,Product2Id,SerialNumber,last_contract_number__c,Service_Start_Date_Min__c, Service_End_Date_Max__c,InstallDate,Bundle_Support__c FROM Asset WHERE AccountId = :GetAccount.AccountId and last_contract_number__c = :GetContract.Name  Order by Service_End_Date_Max__c Desc  Limit 1000] );
        } 
       else 
        { 
        this.setCon = new ApexPages.StandardSetController( [SELECT Id, AccountId,Product2Id,SerialNumber,last_contract_number__c,Service_Start_Date_Min__c, Service_End_Date_Max__c,InstallDate,Bundle_Support__c FROM Asset WHERE AccountId = '0013000000DULXG' Order by Service_End_Date_Max__c Desc Limit 1000] );                                            
        }    
      }
      
      catch(Exception e) {  
       this.setCon = new ApexPages.StandardSetController( [SELECT Id, AccountId,Product2Id,SerialNumber,last_contract_number__c,Service_Start_Date_Min__c, Service_End_Date_Max__c,InstallDate,Bundle_Support__c FROM Asset WHERE AccountId = '0013000000DULXG' Order by Service_End_Date_Max__c Desc Limit 1000] );                                            
        }            
       
        if(this.setCon != null){                                        
        this.setCon.setpageNumber(1);
        this.setCon.setPageSize(25);
        }
   } 
   
       
    /*
    *   handle item selected
    */
    public void doSelectItem(){        
        this.selectedContactIds.add(this.contextItem);        
    }
    
    public void doSelectItem2(){        
        this.selectedContactIds2.add(this.contextItem2);        
    }
    
    
    /*
    *   handle item deselected
    */
    public void doDeselectItem(){        
        this.selectedContactIds.remove(this.contextItem);        
    }
    
    public void doDeselectItem2(){        
        this.selectedContactIds2.remove(this.contextItem2);        
    }
    
    
    /*
    *   return count of selected items
    */
    public Integer getSelectedCount(){
        
        return this.selectedContactIds.size();
        
    }
    
    
    /*
    *   advance to next page
    */
    public void doNext(){        
        if(this.setCon.getHasNext())
            this.setCon.next();
          }     
    
    
    /*
    *   advance to previous page
    */
    public void doPrevious(){        
        if(this.setCon.getHasPrevious())
            this.setCon.previous();          
    }
    
    //public List<CCWRowItem> rows = new List<CCWRowItem>();
    
    public List<CCWRowItem> rows {get; set;}
    /*
    *   return current page of groups
    */
    public List<CCWRowItem> getContacts(){        
       try  
        {
        rows = new List<CCWRowItem>();      
        
        for(sObject r : this.setCon.getRecords()){
            Asset c = (Asset)r;
            
            CCWRowItem row = new CCWRowItem(c);
            if(this.selectedContactIds.contains(c.Id)){
                row.IsSelected=true;
                if (this.selectedContactIds2.contains(c.Id)){
                    row.BundelSelected=true;
                    bundsprt=true;
                }
                else {
                    row.BundelSelected=false;
                    bundsprt=false;
                }

            }
            else {
                row.IsSelected=false;
            }
            rows.add(row);            
        }
                
        return rows;
        }
        catch(Exception e) { 
           return null;
             }
        
    }
  
 // Store Selected Records to Object/Table
 public void processSelected() {
    Integer currentPageNumber = setCon.getPageNumber();
    selectedAssets = new List<Asset>();
    list<Temp_Assets__c> TempAssetList = new list<Temp_Assets__c>();  
        
      
     setCon.setpageNumber(1);
     

while(true){
    List<Asset>  TempAssetLists = (List<Asset>)setCon.getRecords();
    for(Asset assetIns : TempAssetLists  ) {
          if(this.selectedContactIds.contains(assetIns.Id)){
             selectedAssets.add(assetIns);
             
             
           }
     }
 if(setCon.getHasNext()){
  setCon.next();
  }
  else{
  break;
  } 
   
}  
        /**********Added by Unnat*********************************/
        //below code should only execute if Expiry term has a value
        Date maxDate=Date.valueOf('2000-1-1');
        Date minDate;
        
        //Calculate the maximum Date off of the selected dates
      
        //finds the latest expiry date out of the selected assets
        for (Asset assets: selectedAssets) {
            if(assets.Service_End_Date_Max__c > maxDate) {
                maxDate=assets.Service_End_Date_Max__c;
            }
        }
        System.debug('== Latest Service end Date is:'+ maxDate);
        minDate = maxDate;
        for (Asset assets: selectedAssets) {
            if(minDate > assets.Service_End_Date_Max__c) {
                minDate=assets.Service_End_Date_Max__c;
            }
        }
        System.debug('== Least Service end Date is:'+ minDate);
        
          
        //Validations 
        if ((selectedAssets.size() < 1 ) || (expireTerms == '0' && GetExpireDate.Expire_Date__c== null )|| (expireTerms != '0' && GetExpireDate.Expire_Date__c!= null ) || (GetDistributor.Primary_Distributor__c == null ) || (GetReseller.Primary_Reseller__c == null ) || (GetOpportunity.Opportunity__c==null && GetNewOpportunity.New_Opportunity__c== null ) || (GetOpportunity.Opportunity__c!=null && GetNewOpportunity.New_Opportunity__c!= null )|| (GetExpireDate.Expire_Date__c < maxDate )) {
        //Validates that atleast one of the assets is selected from the install base
        if(selectedAssets.size() < 1 ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please select atleast one Asset to renew from the Install Base.'));
        }
        //Validates that atleast one of the Expiry Dates needs to have a value
        if(expireTerms == '0' && GetExpireDate.Expire_Date__c== null ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please enter the Expiry Term or Expiry Date for the selected Assets.'));
        }
        //Valation that only of the Expirty Dates can have a value
        else if(expireTerms != '0' && GetExpireDate.Expire_Date__c!= null ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'You can enter a value either in Expiry Date or Expiry Term, but not in both.'));
        }
        //Validation that the Distributor Name is required
        if(GetDistributor.Primary_Distributor__c == null ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please enter a value in Distributor'));
        }
        //Validation that Reseller Name is required
        if(GetReseller.Primary_Reseller__c == null ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please enter a value in Reseller'));
        } 
        //Validation that atleast one Opportunity needs to have a value
        if(GetOpportunity.Opportunity__c==null && GetNewOpportunity.New_Opportunity__c== null ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please enter a value in either of the Opportunity'));
        }
        //Validation that only one of the Opportunities can have a value
        else if(GetOpportunity.Opportunity__c!=null && GetNewOpportunity.New_Opportunity__c!= null ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'You can enter a value either in Opportunity or New Opportunity, but not in both.'));
        }
        //Validation that will check if the Expiry Date has value less than the selected Asset Service End Date
        if(GetExpireDate.Expire_Date__c < maxDate ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Expiry Date that you entered is lower than Service End Date of the Asset'));
        }
        }
        else {
        //below code should only execute if Expiry term has a value
        //Date maxDate=Date.valueOf('2000-1-1');
        //Calculate the maximum Date off of the selected dates
        
        if (ExpireTerms !=null) {
        System.debug('== Expire Terms has a value');
            //finds the latest expiry date out of the selected assets
           /***************************moved this upwards*********************************** 
           for (Asset assets: selectedAssets) {
                if(assets.Service_End_Date_Max__c > maxDate) {
                    maxDate=assets.Service_End_Date_Max__c;
                }
            }
            System.debug('== Latest Service end Date is:'+ maxDate);
            
            //Validation that will check if the Expiry Date has value less than the selected Asset Service End Date
            if(GetExpireDate.Expire_Date__c < maxDate ){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Expiry Date that you entered is lower than Service End Date of the Asset'));
            }
            *********************************************************************************/
            //There will be another condition to add the expiry term to the latest expiry date
            //String a='1 Year';
            System.debug('== ExpireTerms is: '+ ExpireTerms);
            if (ExpireTerms=='1') {
                System.debug('== First if condition');
                maxDate=maxDate.addYears(1);
            }
            else if (ExpireTerms == '3') {
            System.debug('== Second if condition');
                maxDate=maxDate.addYears(3);
            }
            else if (ExpireTerms == '5') {
            System.debug('== third if condition');
                maxDate=maxDate.addYears(5);
            }
            else {
                maxDate= GetExpireDate.Expire_Date__c; 
            }
        }
        else {
        System.debug('== Else condition');
            maxDate= GetExpireDate.Expire_Date__c;   
        } 
        System.debug('== Max Date is: ' + maxDate);
        Integer totalDays = minDate.daysBetween(maxDate); 
        System.debug('== Total days difference is: '+ totalDays);
        /****************Completed by Unnat*****************************/
        
        //checks if the Monthly Quote is going to be more than 36 months and Monthly Quote Checkbox is selected
        /*if (totalDays > 1080 && Monthly_Quote == true ) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Since the Renewals in Months is more than 3 years, please uncheck the Monthly Quote checkbox'));
        }
        else {*/        
            System.debug('=- after the if condition');           
            Account ResellerAct; 
            Account DistributorAct;  
            Opportunity Oppt;           
                                
            for(Asset Act : selectedAssets)
            {               
                Temp_Assets__c TempAsset = new Temp_Assets__c();
                TempAsset.Name = 'Sudhir';
                TempAsset.AccountId__c = Act.AccountId;
                TempAsset.Product__c = Act.Product2Id;
                //Added by Unnat
                TempAsset.Product_lookup__c= Act.Product2Id;
                TempAsset.Asset_Id__c = Act.Id;
                TempAsset.Serial_Number__c = Act.SerialNumber;
                TempAsset.Last_Contract_Number__c = Act.last_contract_number__c; 
                TempAsset.Service_Start_Date__c = Act.Service_Start_Date_Min__c;
                
                //TempAsset.Service_End_Date__c = Act.Service_End_Date_Max__c;
                /***************Added by Unnat********************************************/
                TempAsset.Opp_Close_Date__c = minDate;
                TempAsset.Monthly_Quote__c = Monthly_Quote;
                System.debug('=- Monthly Quote is: ' + monthly_Quote);
                
                if (Act.Service_End_Date_Max__c != null) {
                    TempAsset.Service_End_Date__c = Act.Service_End_Date_Max__c;
                }
                else {
                    TempAsset.Service_End_Date__c = Act.InstallDate;
                }
                
                TempAsset.Install_Date__c = Act.InstallDate;  
                System.debug ('==== Reseller id is: '+ GetReseller.Primary_Reseller__c);
                TempAsset.Reseller__c = GetReseller.Primary_Reseller__c;
                TempAsset.Distributor__c = GetDistributor.Primary_Distributor__c;
                
                /****************Commented by Unnat****************************************************************************
                
                If (GetReseller.AccountId <> NULL) 
                {      
                ResellerAct = [ SELECT Id FROM Account WHERE ID = :GetReseller.Primary_Reseller__c Limit 1];
                TempAsset.Reseller__c = ResellerAct.Id;      
                 System.debug ('==== Reseller id 2 is: '+ ResellerAct.Id);        
                }
               
                If (GetDistributor.AccountId <> NULL )
                {
                DistributorAct = [ SELECT Id FROM Account WHERE ID = :GetDistributor.Primary_Distributor__c Limit 1];
                TempAsset.Distributor__c = DistributorAct.Id;
                }
                
                ****************Completed by Unnat *****************************************************************************/
                If ( GetOpportunity.Opportunity__c <> NULL )
                {
                Oppt = [SELECT Id FROM Opportunity WHERE ID = :GetOpportunity.Opportunity__c Limit 1];
                TempAsset.Existing_Opportunity__c = Oppt.Id;
                }                
                TempAsset.Incumbent_Reseller__c = IncumbentReseller;
                TempAsset.Education__c = Education; 
                //TempAsset.Expiry_Date__c = GetExpireDate.Expire_Date__c;
                TempAsset.Expiry_Date__c= maxDate;
                
                TempAsset.New_Opportunity__c = GetNewOpportunity.New_Opportunity__c;
                TempAsset.Expiry_Term__c = ExpireTerms;
                
                /* Insert Bundel Checkbox Value */                
                if (this.selectedContactIds2.contains(Act.Id)){
                    bundsprt=true;
                }
                else {
                    bundsprt=false;
                }
                
                
                TempAsset.Bundle_Support__c = bundsprt; 
                System.debug('== Bundle Value is: ' + bundsprt);
                
                             //Add the selected Assets to the List
                TempAssetList.add(TempAsset);
            }
                
            Insert TempAssetList;                            
            Redirect();
            
       // } //end of if Condition for check of days more than 3 years
       }
        setCon.setpageNumber(currentPageNumber);
        
    }
    
public pagereference Redirect()
   {

     PageReference pageref = new PageReference('/006m0000002MqNf');   //instead of hardcoded id you can mention opp id by using query
     pageref.setRedirect(true); 
     return pageref;
    }
      
    
    /*
    *   return whether previous page exists
    */
    public Boolean getHasPrevious(){       
       try  
        {
        return this.setCon.getHasPrevious();         
        }
        catch(Exception e) { 
           return false;
             }
    }
    
    
    /*
    *   return whether next page exists
    */
    public Boolean getHasNext(){       
    try  
        {
        return this.setCon.getHasNext();
        }
      catch(Exception e) { 
           return false;
             }
    }

    
    /*
    *   return page number
    */
    public Integer getPageNumber(){   
    try  
        {     
        return this.setCon.getPageNumber();        
    }
    catch(Exception e) { 
           return 1;
             }
    }

    
    /*
    *    return total pages
    */
    Public Integer getTotalPages(){
    Decimal totalSize;
    Decimal pageSize;
    Decimal pages;
    try  
        { 
          totalSize = this.setCon.getResultSize();
          pageSize = this.setCon.getPageSize();      
          pages = totalSize/pageSize;
          return (Integer)pages.round(System.RoundingMode.CEILING);      
        }
         catch(Exception e) { 
           return 1;
             }
    }

 
    
    /*
    *   helper class that represents a row
    */
    public with sharing class CCWRowItem{
        
        public Asset tContact{get;set;}
        public Boolean IsSelected{get;set;}
        public Boolean BundelSelected{get;set;}
         
        public CCWRowItem(Asset c){
            this.tContact=c;            
            this.IsSelected=false;
            this.BundelSelected=false;
        }
        
    } 
  
       
     
    
}


Thanks
Sudhir

 

praveen murugesanpraveen murugesan
Hi Sudhir,

public pagereference Redirect()
 {

 PageReference pageref = new PageReference('/XXXXX');   //instead of hardcoded id you need to mention opportunity id
pageref.setRedirect(true);
return pageref;
 }
Sudhir_MeruSudhir_Meru

Hi Praveen, 

  For testing I tried as below even this is not working

public pagereference Redirect()
{

PageReference pageref = new PageReference('https://www.google.co.in');   //instead of hardcoded id you need to mention opportunity id
pageref.setRedirect(true);
return pageref;
}


I want to know how to call this Redirect() funcation Please suggest me 

Thanks

Sudhir

praveen murugesanpraveen murugesan
Hi Sudhir,

Above mentioned code will not work dude, Because here you have added PageReference('https://www.google.co.in');

but it should be PageReference pageref = new PageReference('/any id');

For eg: Click accounts tab select one account get the ID from the url put that here.

Thanks.
Sudhir_MeruSudhir_Meru
Hi Praveen, 

  Please find the code below I am adding opportunity Id I am calling Redirect() funcation inside another function processselected but this is not working Please check

// Store Selected Records to Object/Table
 public void processSelected() {
    Integer currentPageNumber = setCon.getPageNumber();
    selectedAssets = new List<Asset>();
    list<Temp_Assets__c> TempAssetList = new list<Temp_Assets__c>();  
        
      
     setCon.setpageNumber(1);
     

while(true){
    List<Asset>  TempAssetLists = (List<Asset>)setCon.getRecords();
    for(Asset assetIns : TempAssetLists  ) {
          if(this.selectedContactIds.contains(assetIns.Id)){
             selectedAssets.add(assetIns);
             
             
           }
     }
 if(setCon.getHasNext()){
  setCon.next();
  }
  else{
  break;
  } 
   
}  
        /**********Added by Unnat*********************************/
        //below code should only execute if Expiry term has a value
        Date maxDate=Date.valueOf('2000-1-1');
        Date minDate;
        
        //Calculate the maximum Date off of the selected dates
      
        //finds the latest expiry date out of the selected assets
        for (Asset assets: selectedAssets) {
            if(assets.Service_End_Date_Max__c > maxDate) {
                maxDate=assets.Service_End_Date_Max__c;
            }
        }
        System.debug('== Latest Service end Date is:'+ maxDate);
        minDate = maxDate;
        for (Asset assets: selectedAssets) {
            if(minDate > assets.Service_End_Date_Max__c) {
                minDate=assets.Service_End_Date_Max__c;
            }
        }
        System.debug('== Least Service end Date is:'+ minDate);
        
          
        //Validations 
        if ((selectedAssets.size() < 1 ) || (expireTerms == '0' && GetExpireDate.Expire_Date__c== null )|| (expireTerms != '0' && GetExpireDate.Expire_Date__c!= null ) || (GetDistributor.Primary_Distributor__c == null ) || (GetReseller.Primary_Reseller__c == null ) || (GetOpportunity.Opportunity__c==null && GetNewOpportunity.New_Opportunity__c== null ) || (GetOpportunity.Opportunity__c!=null && GetNewOpportunity.New_Opportunity__c!= null )|| (GetExpireDate.Expire_Date__c < maxDate )) {
        //Validates that atleast one of the assets is selected from the install base
        if(selectedAssets.size() < 1 ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please select atleast one Asset to renew from the Install Base.'));
        }
        //Validates that atleast one of the Expiry Dates needs to have a value
        if(expireTerms == '0' && GetExpireDate.Expire_Date__c== null ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please enter the Expiry Term or Expiry Date for the selected Assets.'));
        }
        //Valation that only of the Expirty Dates can have a value
        else if(expireTerms != '0' && GetExpireDate.Expire_Date__c!= null ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'You can enter a value either in Expiry Date or Expiry Term, but not in both.'));
        }
        //Validation that the Distributor Name is required
        if(GetDistributor.Primary_Distributor__c == null ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please enter a value in Distributor'));
        }
        //Validation that Reseller Name is required
        if(GetReseller.Primary_Reseller__c == null ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please enter a value in Reseller'));
        } 
        //Validation that atleast one Opportunity needs to have a value
        if(GetOpportunity.Opportunity__c==null && GetNewOpportunity.New_Opportunity__c== null ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please enter a value in either of the Opportunity'));
        }
        //Validation that only one of the Opportunities can have a value
        else if(GetOpportunity.Opportunity__c!=null && GetNewOpportunity.New_Opportunity__c!= null ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'You can enter a value either in Opportunity or New Opportunity, but not in both.'));
        }
        //Validation that will check if the Expiry Date has value less than the selected Asset Service End Date
        if(GetExpireDate.Expire_Date__c < maxDate ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Expiry Date that you entered is lower than Service End Date of the Asset'));
        }
        }
        else {
        //below code should only execute if Expiry term has a value
        //Date maxDate=Date.valueOf('2000-1-1');
        //Calculate the maximum Date off of the selected dates
        
        if (ExpireTerms !=null) {
        System.debug('== Expire Terms has a value');
            //finds the latest expiry date out of the selected assets
           /***************************moved this upwards*********************************** 
           for (Asset assets: selectedAssets) {
                if(assets.Service_End_Date_Max__c > maxDate) {
                    maxDate=assets.Service_End_Date_Max__c;
                }
            }
            System.debug('== Latest Service end Date is:'+ maxDate);
            
            //Validation that will check if the Expiry Date has value less than the selected Asset Service End Date
            if(GetExpireDate.Expire_Date__c < maxDate ){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Expiry Date that you entered is lower than Service End Date of the Asset'));
            }
            *********************************************************************************/
            //There will be another condition to add the expiry term to the latest expiry date
            //String a='1 Year';
            System.debug('== ExpireTerms is: '+ ExpireTerms);
            if (ExpireTerms=='1') {
                System.debug('== First if condition');
                maxDate=maxDate.addYears(1);
            }
            else if (ExpireTerms == '3') {
            System.debug('== Second if condition');
                maxDate=maxDate.addYears(3);
            }
            else if (ExpireTerms == '5') {
            System.debug('== third if condition');
                maxDate=maxDate.addYears(5);
            }
            else {
                maxDate= GetExpireDate.Expire_Date__c; 
            }
        }
        else {
        System.debug('== Else condition');
            maxDate= GetExpireDate.Expire_Date__c;   
        } 
        System.debug('== Max Date is: ' + maxDate);
        Integer totalDays = minDate.daysBetween(maxDate); 
        System.debug('== Total days difference is: '+ totalDays);
        /****************Completed by Unnat*****************************/
        
        //checks if the Monthly Quote is going to be more than 36 months and Monthly Quote Checkbox is selected
        /*if (totalDays > 1080 && Monthly_Quote == true ) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Since the Renewals in Months is more than 3 years, please uncheck the Monthly Quote checkbox'));
        }
        else {*/        
            System.debug('=- after the if condition');           
            Account ResellerAct; 
            Account DistributorAct;  
            Opportunity Oppt;           
                                
            for(Asset Act : selectedAssets)
            {               
                Temp_Assets__c TempAsset = new Temp_Assets__c();
                TempAsset.Name = 'Sudhir';
                TempAsset.AccountId__c = Act.AccountId;
                TempAsset.Product__c = Act.Product2Id;
                //Added by Unnat
                TempAsset.Product_lookup__c= Act.Product2Id;
                TempAsset.Asset_Id__c = Act.Id;
                TempAsset.Serial_Number__c = Act.SerialNumber;
                TempAsset.Last_Contract_Number__c = Act.last_contract_number__c; 
                TempAsset.Service_Start_Date__c = Act.Service_Start_Date_Min__c;
                
                //TempAsset.Service_End_Date__c = Act.Service_End_Date_Max__c;
                /***************Added by Unnat********************************************/
                TempAsset.Opp_Close_Date__c = minDate;
                TempAsset.Monthly_Quote__c = Monthly_Quote;
                System.debug('=- Monthly Quote is: ' + monthly_Quote);
                
                if (Act.Service_End_Date_Max__c != null) {
                    TempAsset.Service_End_Date__c = Act.Service_End_Date_Max__c;
                }
                else {
                    TempAsset.Service_End_Date__c = Act.InstallDate;
                }
                
                TempAsset.Install_Date__c = Act.InstallDate;  
                System.debug ('==== Reseller id is: '+ GetReseller.Primary_Reseller__c);
                TempAsset.Reseller__c = GetReseller.Primary_Reseller__c;
                TempAsset.Distributor__c = GetDistributor.Primary_Distributor__c;
                
                /****************Commented by Unnat****************************************************************************
                
                If (GetReseller.AccountId <> NULL) 
                {      
                ResellerAct = [ SELECT Id FROM Account WHERE ID = :GetReseller.Primary_Reseller__c Limit 1];
                TempAsset.Reseller__c = ResellerAct.Id;      
                 System.debug ('==== Reseller id 2 is: '+ ResellerAct.Id);        
                }
               
                If (GetDistributor.AccountId <> NULL )
                {
                DistributorAct = [ SELECT Id FROM Account WHERE ID = :GetDistributor.Primary_Distributor__c Limit 1];
                TempAsset.Distributor__c = DistributorAct.Id;
                }
                
                ****************Completed by Unnat *****************************************************************************/
                If ( GetOpportunity.Opportunity__c <> NULL )
                {
                Oppt = [SELECT Id FROM Opportunity WHERE ID = :GetOpportunity.Opportunity__c Limit 1];
                TempAsset.Existing_Opportunity__c = Oppt.Id;
                }                
                TempAsset.Incumbent_Reseller__c = IncumbentReseller;
                TempAsset.Education__c = Education; 
                //TempAsset.Expiry_Date__c = GetExpireDate.Expire_Date__c;
                TempAsset.Expiry_Date__c= maxDate;
                
                TempAsset.New_Opportunity__c = GetNewOpportunity.New_Opportunity__c;
                TempAsset.Expiry_Term__c = ExpireTerms;
                
                /* Insert Bundel Checkbox Value */                
                if (this.selectedContactIds2.contains(Act.Id)){
                    bundsprt=true;
                }
                else {
                    bundsprt=false;
                }
                
                
                TempAsset.Bundle_Support__c = bundsprt; 
                System.debug('== Bundle Value is: ' + bundsprt);
                
                             //Add the selected Assets to the List
                TempAssetList.add(TempAsset);
            }
                
            Insert TempAssetList;                            
            Redirect();
            
       // } //end of if Condition for check of days more than 3 years
       }
        setCon.setpageNumber(currentPageNumber);
        
    }
    
public pagereference Redirect()
   {

     PageReference pageref = new PageReference('/006m0000002MqNf');   //instead of hardcoded id you can mention opp id by using query
     pageref.setRedirect(true); 
     return pageref;
    }


 Thanks
Sudhir
Arunkumar RArunkumar R
Can you try like this,

public class demo
{

public string baseURL{get;set;}
Public String existingId{get;set;}

public static void processSelected()
{
// Your function

}
 public PageReference pageRefMethod() {

//call your action method
 processSelected();

existingId = '006m0000002MqNf';
baseUrl = URL.getSalesforceBaseUrl().toExternalForm()+'/';

  PageReference send = new PageReference(baseURL + existingId);
    send.setRedirect(true);
    return send;

    }

}


In your visualforce page,

<apex:commandButton value="SAve" action="{!pageRefMethod}"/>


This was selected as the best answer
Sudhir_MeruSudhir_Meru

Hi Arun, 

  Thank you very much you are genious 

Thanks

Sudhir