• Jina Chetia
  • NEWBIE
  • 0 Points
  • Member since 2008


  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 28
    Questions
  • 24
    Replies

Hi,

 

I am getting a apex heap size error in my batch apex class. - System.LimitException: Apex heap size too large: 6030143.

The records that needs to be processed are in the range of 10k to 50K. I think it is because of the map that I am using in my code.

 This is how my code looks like

global class CreatePortfolioReport implements Database.Batchable<sObject>, Database.Stateful{
	public String query;
	global String email;

	Map<String, Purchase_Sales_Report__c[]> purchaseMap = new Map<String, Purchase_Sales_Report__c[]>();
	Map<String, Purchase_Sales_Report__c[]> salesMap = new Map<String, Purchase_Sales_Report__c[]>();
	
	
	global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<sObject> scope){
    	 for(sObject s: scope){
    	 	Purchase_Sales_Report__c ps = (Purchase_Sales_Report__c)s;
    	 	if(ps.Transaction__c != null){
	    	 	if(ps.Transaction__c.equals('Purchase')){
		    	 	if(!purchaseMap.isEmpty() && purchaseMap.containsKey(ps.Unique_Name__c)){
		    	 		purchaseMap.get(ps.Unique_Name__c).add(ps);
		    	 	}
		    	 	else{
		    	 		List<Purchase_Sales_Report__c> newList = new List<Purchase_Sales_Report__c>();
		    	 		newList.add(ps);
		    	 		purchaseMap.put(ps.Unique_Name__c, newList);
		    	 	}
	    	   }
	    	   else if(ps.Transaction__c.equals('Sales')){
	    	   		if(!salesMap.isEmpty() && salesMap.containsKey(ps.Unique_Name__c)){
		    	 		salesMap.get(ps.Unique_Name__c).add(ps);
		    	 	}
		    	 	else{
		    	 		List<Purchase_Sales_Report__c> newList = new List<Purchase_Sales_Report__c>();
		    	 		newList.add(ps);
		    	 		salesMap.put(ps.Unique_Name__c, newList);
		    	 	}
	    	   }
    	 	}
    	 } 
    	 System.debug('Purchase Map size'+purchaseMap.size());
    	 System.debug('Sales Map size'+salesMap.size());
    }
    
    global void finish(Database.BatchableContext BC){
    	Map<String, Double> salesUnits = new Map<String, Double>();
    	Map<String, Double> purchaseUnits = new Map<String, Double>();
    	Map<String, Portfolio_Report__c> portfolioMap = new Map<String, Portfolio_Report__c>();
    	List<Temp_Purchase_Report__c> purchaseList = new List<Temp_Purchase_Report__c>();
    	for(String uniqueName: salesMap.keySet()){
  			Double units = 0;
  			Double purchaseAmount = 0;
  			for(Purchase_Sales_Report__c ps:salesMap.get(uniqueName)){
  				
  				if(ps.Units__c != null){
  					units += ps.Units__c;
  				}
  			}
  			salesUnits.put(uniqueName, units);
  		}
  		System.debug('Sales Map'+salesMap.size());
  		for(String uniqueName: purchaseMap.keySet()){
  			
  	        Double units;
  			if(salesUnits.containsKey(uniqueName)){
  				units = Math.abs(salesUnits.get(uniqueName));
  			}
  			Double pUnits = 0;
  			Double product = 0;
  			Double portUnits = 0;
  			Double portAmount = 0;
  			Double divReinvAmount = 0;
  			Double divAmount = 0;
  			Double stpAmount = 0;
  			Boolean entityFlag = true;
  			Id entity;
  			String folio;
  			String assetClass;
  			String schemeName;
  			for(Purchase_Sales_Report__c ps:purchaseMap.get(uniqueName)){
  				
  				if(units != null && pUnits != units){
  					if(ps.Units__c != null){
  						pUnits += ps.Units__c;
  					}
  					
  				}
  				else{
  					
  					if(ps.Units__c != null){
  						portUnits += ps.Units__c;
  					}
  					if(ps.Amount__c != null && ps.Type__c != null){
  						
  						if(ps.Type__c.equalsIgnoreCase('NOR') || ps.Type__c.equalsIgnoreCase('SIP')){
  							portAmount += ps.Amount__c;
  						}
  						else if(ps.Type__c.equalsIgnoreCase('DIR')){
  							divReinvAmount += ps.Amount__c;
  						}
  						else if(ps.Type__c.equalsIgnoreCase('STI') || ps.Type__c.equalsIgnoreCase('SWI')){
  							stpAmount += ps.Amount__c;
  						}
  						else if(ps.Type__c.equalsIgnoreCase('DVP')){
  							divAmount += ps.Amount__c;
  						}
  					}
  					if(ps.Product__c != null){
  						product += ps.Product__c;
  					}
  					if(entityFlag){
	  					entity = ps.Entity__c;
	  					folio = ps.Folio_Number__c;
	  					assetClass = ps.Asset_Class__c;
	  					entityFlag = false;
	  					schemeName = ps.Scheme_Name__c;
  					}
  					System.debug('Create Port Units'+portUnits+'Amount'+portAmount+'Product'+product);
  				}
  				
  			}
  			if(portUnits != 0 && product != 0 && (portAmount != 0 || divAmount !=0 || divReinvAmount !=0 || divAmount != 0) ){
  				Temp_Purchase_Report__c pr = new Temp_Purchase_Report__c(Entity__c= entity, 
  																		 Folio_Number__c = folio, 
  																		 Asset_Class__c = assetClass,
  																		 UniqueName__c = uniqueName, 
  																		 Purchase_Amount__c= portAmount, 
  																		 Units_Quanitity__c = portUnits, 
  																		 Product__c = product,
  																		 Dividend_Reinvested__c = divReinvAmount,
  																		 Dividend__c = divAmount,
  																		 STP_Switch__c = stpAmount,
  																		 Scheme_Scrip_Name__c = schemeName);
  				purchaseList.add(pr);
  			}
  		}
  		System.debug('Purchase List'+purchaseList.size());
  		
  		upsert purchaseList UniqueName__c;
  		  		
  		AsyncApexJob a = [Select Id, 
                                 Status,
                                 NumberOfErrors, 
                                 JobItemsProcessed,  
                                 TotalJobItems, 
                                 CreatedBy.Email 
                                 from AsyncApexJob 
                                 where Id =:BC.getJobId()];
        // Create and send an email with the results of the batch.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {email});
        mail.setReplyTo('');
        mail.setSenderDisplayName('Batch Processing');  
        mail.setSubject('Create Portfolio Report ' + a.Status);
        mail.setPlainTextBody('The batch apex job processed ' + a.TotalJobItems +   ' batches with ' + a.NumberofErrors + ' failures.');
    
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
  		
    }
}

 As I require the map for processing the data in my finish method, I cannot think of any other option to implement it.

 

Can you please suggest me ways to avoid the error?

 

Thanks,

Jina

Hi ,

 

I have written a batch apex to create/update  custom object records. I have two custom objects Purchase_Sales_Report__c and Portfolio_Report__c. Portfolio_Report__c is basically a summary of Purchase_Sales_Report__c records based on a Unique Key. They are both child of the Account object.

 

Every day I get a feed of Purchase_Sales_Report__c objects and based on those records I either need to create a new Portfolio_Report__c record or update the existing record based on a Unique key.

 

In the Database.queryLocator I send all the Purchase_Sales_Report__c records but inorder to update the existing Portfolio_Report__c report, I also require a list of all the existing Portfolio_Report__c records where I face an issue of 'Too many query rows 100001' as the number of records returned is more than 10 k.

 

here is my piece of code. The one in red is where I get an error,

 

 

global class CreateSummaryReport implements Database.Batchable<sObject>, Database.Stateful {
    global String query; 
    global Map<String, Portfolio_Report__c>  existingPortMap = new Map<String, Portfolio_Report__c>();
    global Map<String, Double> purchaseAmountMap = new Map<String, Double>();
    global Map<String, Double> productMap = new Map<String, Double>();
    global Map<String, Double> unitsMap = new Map<String, Double>();
    global Map<String, Purchase_Sales_Report__c> otherDetailsMap = new Map<String, Purchase_Sales_Report__c>();
    global String email;
    
    global CreateSummaryReport(){
        for(Portfolio_Report__c por: [Select Gain__c, 
                                            Units_Quanitity__c,
                                            Scheme_Scrip_Name__c, 
                                            Purchase_Amount__c, 
                                            Portfolio_Type__c, 
                                            Folio_Number__c, 
                                            Current_Value__c,
                                            Absolute_Ret__c,
                                            Annualized_Ret__c, 
                                            UniqueName__c,
                                            Dividend_Reivestment__c,
                                            Transaction_Type__c,
                                            Nav_p__c
                                            From Portfolio_Report__c] ){
            existingPortMap.put(por.UniqueName__c, por);
            
        }
        //email = email;
    }
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<sObject> scope){
       
        for(sObject s: scope){
            Purchase_Sales_Report__c ps = (Purchase_Sales_Report__c)s;
            if(purchaseAmountMap.containsKey(ps.Unique_Name__c)){
            	if(ps.Amount__c != null){
	        		Double d = ps.Amount__c + purchaseAmountMap.get(ps.Unique_Name__c);
	                purchaseAmountMap.put(ps.Unique_Name__c, d);
            	}
            	                
            }
            else {
                   if(ps.Amount__c == null)
                   {
                   		ps.Amount__c = 0;
                   }
                purchaseAmountMap.put(ps.Unique_Name__c, ps.Amount__c);
            }
            if(productMap.containsKey(ps.Unique_Name__c)){
            	if(ps.Product__c != null) {
	                Double d = ps.Product__c + productMap.get(ps.Unique_Name__c);
	                productMap.put(ps.Unique_Name__c, d);
            	}
                
            }
            else {
                  if(ps.Product__c == null)
                  {
                  	ps.Product__c = 0;
                  }
                productMap.put(ps.Unique_Name__c, ps.Product__c);
            }
            if(unitsMap.containsKey(ps.Unique_Name__c)){
            	if(ps.Units__c != null){
	                Double d = ps.Units__c + unitsMap.get(ps.Unique_Name__c);
	                unitsMap.put(ps.Unique_Name__c, d);
            	}
                
            }
            else {
                  if(ps.Units__c == null)
                  {
                  	ps.Units__c = 0;
                  }
                unitsMap.put(ps.Unique_Name__c, ps.Units__c);
            }
            if(!otherDetailsMap.containsKey(ps.Unique_Name__c)){
                otherDetailsMap.put(ps.Unique_Name__c, ps);
            }
        }
        
    }
    global void finish(Database.BatchableContext BC){
        List<Portfolio_Report__c> updateList = new List<Portfolio_Report__c>();
        List<Portfolio_Report__c> newList = new List<Portfolio_Report__c>();
        
        for(String s: purchaseAmountMap.keySet()){
            if(existingPortMap.containsKey(s)){
                Portfolio_Report__c pr = existingPortMap.get(s);
                pr.Purchase_Amount__c = purchaseAmountMap.get(s);
                pr.Product__c = productMap.get(s);
                pr.Units_Quanitity__c = unitsMap.get(s);
                updateList.add(pr);
            }
            else {
                Portfolio_Report__c pr = new Portfolio_Report__c(UniqueName__c=s, 
                                                                 Scheme_Scrip_Name__c=otherDetailsMap.get(s).Scheme_Name__c,
                                                                 Folio_Number__c = otherDetailsMap.get(s).Folio_Number__c,
                                                                 Entity__c = otherDetailsMap.get(s).Entity__c,
                                                                 Product__c = productMap.get(s),
                                                                 Units_Quanitity__c = unitsMap.get(s),
                                                                 Purchase_Amount__c = purchaseAmountMap.get(s));
                newList.add(pr);
            }
        }
        
        insert newList;
        update updateList;
        
        AsyncApexJob a = [Select Id, 
                                 Status,
                                 NumberOfErrors, 
                                 JobItemsProcessed,  
                                 TotalJobItems, 
                                 CreatedBy.Email 
                                 from AsyncApexJob 
                                 where Id =:BC.getJobId()];
        // Create and send an email with the results of the batch.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {email});
        mail.setReplyTo('tech@ffreedom.in');
        mail.setSenderDisplayName('Batch Processing');  
        mail.setSubject('Detailed Portfolio Report Update ' + a.Status);
        mail.setPlainTextBody('The batch apex job processed ' + a.TotalJobItems +   ' batches with ' + a.NumberofErrors + ' failures.');
    
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

 

Can someone please give me a workaround for this?

 

Many Thanks,

Jina

 

 

Hi,

I would like to introduce the Ideas tab in our website which is built in Force.com sites but would like to change the look and feel of the Ideas Home page. To give an example, we would like to do something similar to what Star Bucks had done, giving it our own theme.

While going thru the internet, I found this presentation https://docs.google.com/present/view?id=agqxwgjz4qr3_621fpt7gzff but I could find any 'Ideas Base Theme' in Appexchange. Later came to know that it was just a pilot pahse.

 

Can someone please guide me with the steps on how to do that? Is it completely Visualforce where in all the backend functionality like posting idea, voting count is done thru a custom controller? Are there any APIs available which will ease the customization process?

 

Many Thanks,

Jina

Hi,

 

I am getting 'Too many script statements: 50001' exception in my trigger when I do a mass insert. I have not put any DML statements inside any for loop but still I am getting the error.

 

I have a object named Goal and the trigger is on insert. I need to insert all junction object records associated with the Goal object whenever any Goal record is inserted. There are 3 junction objects associated with the Goal - Insurance/Asset/PortfolioReport.

 

Here is the piece of code

 

trigger CreateGoalAssociations on Goal__c (after insert) {
	List<GoalAssetAssociation__c> assetList = new List<GoalAssetAssociation__c>();
	List<GoalInsuranceAssociation__c> insuranceList = new List<GoalInsuranceAssociation__c>();
	List<GoalIAULIPAssociation__c> pReport = new List<GoalIAULIPAssociation__c>();
	Map<Id, Id> entityIds = new Map<Id, Id>();
	Double d= 0;
	Map<Id, Id> goalAccountMap = new Map<Id, Id>();
	List<Goal__c> goalList = new List<Goal__c>();
	
	for(Goal__c g:Trigger.new){
		goalAccountMap.put(g.Id, g.Entity__c);
		goalList.add(g);
	}
    for(Account a: [select Id,Parent_Entity__c from Account where Parent_Entity__c IN :goalAccountMap.values()]){
		entityIds.put(a.Id, a.Id);
	}
    for(Asset__c a: [select Id, Asset_Type__c from Asset__c where Entity__c IN :goalAccountMap.values()
    					OR Entity__c IN :entityIds.keySet()]){
    	
    	for(Goal__c g: goalList){
    		GoalAssetAssociation__c gA = new GoalAssetAssociation__c(Goal__c = g.Id, Asset__c = a.Id, Allocation__c = d);
    		assetList.add(gA);
    	}
    }
    
    for(Insurance__c i: [select Id, Policy_Number_or_Name__c from Insurance__c where Entity__c IN :goalAccountMap.values()
    						OR Entity__c IN :entityIds.keySet()]){
    	for(Goal__c g:goalList){
    		GoalInsuranceAssociation__c gI = new GoalInsuranceAssociation__c(Goal__c = g.Id, Insurance__c = i.Id, Allocation__c = d);
    		insuranceList.add(gI);
    	}
    	
    }
    
    for(Portfolio_Report__c p: [select Id, Portfolio_Type__c  from Portfolio_Report__c where Entity__c IN :goalAccountMap.values()
    							OR Entity__c IN :entityIds.keySet()]){
    	for(Goal__c g:goalList){
    		GoalIAULIPAssociation__c gP = new GoalIAULIPAssociation__c(Goal__c = g.Id, Portfolio_Report__c = p.Id, Allocation__c = d);
    		pReport.add(gP);
    	}
    }
     insert assetList;
     insert insuranceList;
     insert pReport;
     
}

 

Is there any way I can modify the code to avoid the errors. I have highligted the places where I am getting the error.

 

Any help on this will be very much appreciated.

 

Many Thanks,

Jina

Hi,

 

I have to prepare two financial reports on nightly basis based on the every day feed that I get into salesforce. Here are the details -

 

1. There are two objects in salesforce Purchase Report and Portfolio Report and they are linked to the Account object. Account is the master for the two objects

 

2. Every day I get a feed of the Purchase Report which details out the money invested, date etc. Each record here requires some net gain % calculation which I am currently handling it thru a batch process.

 

3. Now based on the Purchase Report, I have to prepare  the Portfolio Report records which is the summary of the Purchse Report records..

  For e.g. - Account A has 100 records in the Purchase Report,out which there are 10 unique products..i.e. 10 records each for each product.

  So my summary report should generate 10 records, summing the total amount spent for 10 records and then other calculations like net gain % etc. Also, if there is already a record for the products in Portfolio Report object, it should just update the record instead of creating a new record. This will be something like the mutual find summary report and this update should run on nightly basis.

 

4. The daily feed that I would get may have around 50 K records.

 

I am confused on what approach should I take. If I use batch process, one batch will contain only 200 records and that might not include all the records for each product. I can store the summation on a stateful class variable but then how do I handle the after processing of data.

Should I do all my post calculations of calculating gain based on the summation in the 'finsh' method and upsert the records there? Is this a good a approach or there is some other way of doing it?

 

Many Thanks,

Jina

Hi,

 

I want to override the Convert Lead Button inorder to do a Javascript validation. I want the user to go ahead with Convert only if the Status is 'Closed -Converted'.

 

I have written an S-Control to do so, the check works fine but when the page is redirected to the leadConvert.jsp it goes into infinite loop.

 

Here is the code -

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <script type="text/javascript" src="/js/functions.js"></script> <script src="/soap/ajax/11.1/connection.js"></script> <script> function pageInit() { var leadStatus= "{!Lead.Status}"; if(leadStatus== 'Closed - Converted') { this.parent.frames.location.replace("/lead/leadconvert.jsp?retURL={!Lead.Id}&id={!Lead.Id}"); } else { alert('Error Message'); this.parent.frames.location.replace("/{!Lead.Id}"); } } pageInit(); </script> </html>

 

Can someone please help me in solving this?

 

Thanks,

Jina

Hi,

 

I have trigger on a custom object CPP__c on update where I am creating history records for that object if any desired value changes in the updated record. I am not using nay new id while inserting but still I get this error

 

Update_CPP_change_history: execution of AfterUpdate

caused by: System.DmlException: Insert failed. First exception on row 0 with id a04R000000141WOIAY; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

 

The trigger works fine on a single update, it only fails when I try to do a mass update through Apex Data Loader by matching the lookup fields on the CPP__c object.

 

Can someone please help me in solving this issue? I have inserting the code snippet below

 

trigger Update_CPP_change_history on CPP__c (before delete, after insert, after update) { List<CPP_Change_History__c> CPPs = new List<CPP_Change_History__c>{}; if (Trigger.isInsert) { for (CPP__c a : Trigger.new) { CPP_Change_History__c ch = new CPP_Change_History__c( Account_Name__c = a.Account__c, CPP__c = a.id, Business_Lost_Reason_New__c = a.Business_Lost_Reason__c, Business_Under_Threat_Reason_New__c = a.Business_Under_Threat_Reason__c, Business_Won_Reason_New__c = a.Business_Won_Reason__c, Change_Date__c = System.today(), Price_New__c = a.per_UOM__c, Status_New__c = a.Current_Status__c, Supplier_New__c = a.Supplier_Name__c, Producer_New__c = a.Producer_Name__c, Volume_New__c = a.Annual_KGs__c ); CPPs.add(ch); } insert CPPs; } else if (Trigger.isUpdate) { for (Integer i = 0; i < Trigger.new.size(); i++) { if ((Trigger.old[i].Supplier_Name__c != Trigger.new[i].Supplier_Name__c)|| (Trigger.old[i].Producer_Name__c != Trigger.new[i].Producer_Name__c) || (Trigger.old[i].Business_Lost_Reason__c != Trigger.new[i].Business_Lost_Reason__c) || (Trigger.old[i].Business_Under_Threat_Reason__c != Trigger.new[i].Business_Under_Threat_Reason__c)|| (Trigger.old[i].Business_Won_Reason__c != Trigger.new[i].Business_Won_Reason__c) || (Trigger.old[i].per_UOM__c != Trigger.new[i].per_UOM__c) || (Trigger.old[i].Current_Status__c != Trigger.new[i].Current_Status__c)|| (Trigger.old[i].Annual_KGs__c != Trigger.new[i].Annual_KGs__c) ) { //Creat CPP History only if certain fields change CPP_Change_History__c ch = new CPP_Change_History__c( CPP__c = Trigger.new[i].id, Change_Date__c = System.today(), Account_Name__c = Trigger.new[i].Account__c); if(Trigger.old[i].Supplier_Name__c != Trigger.new[i].Supplier_Name__c){ ch.Supplier_New__c = Trigger.new[i].Supplier_Name__c; ch.Supplier_Old__c = Trigger.old[i].Supplier_Name__c; } if(Trigger.old[i].Producer_Name__c != Trigger.new[i].Producer_Name__c){ ch.Producer_New__c = Trigger.new[i].Producer_Name__c; ch.Producer_Old__c = Trigger.old[i].Producer_Name__c; } if(Trigger.old[i].Business_Lost_Reason__c != Trigger.new[i].Business_Lost_Reason__c){ ch.Business_Lost_Reason_New__c = Trigger.new[i].Business_Lost_Reason__c; ch.Business_Lost_Reason_Old__c = Trigger.old[i].Business_Lost_Reason__c; } if(Trigger.old[i].Business_Under_Threat_Reason__c != Trigger.new[i].Business_Under_Threat_Reason__c){ ch.Business_Under_Threat_Reason_New__c = Trigger.new[i].Business_Under_Threat_Reason__c; ch.Business_Under_Threat_Reason_Old__c = Trigger.old[i].Business_Under_Threat_Reason__c; } if(Trigger.old[i].Business_Won_Reason__c != Trigger.new[i].Business_Won_Reason__c){ ch.Business_Won_Reason_New__c = Trigger.new[i].Business_Won_Reason__c; ch.Business_Won_Reason_Old__c = Trigger.old[i].Business_Won_Reason__c; } if(Trigger.old[i].per_UOM__c != Trigger.new[i].per_UOM__c){ ch.Price_New__c = Trigger.new[i].per_UOM__c; ch.Price_Old__c = Trigger.old[i].per_UOM__c; } if(Trigger.old[i].Current_Status__c != Trigger.new[i].Current_Status__c){ ch.Status_New__c = Trigger.new[i].Current_Status__c; ch.Status_Old__c = Trigger.old[i].Current_Status__c; } if(Trigger.old[i].Annual_KGs__c != Trigger.new[i].Annual_KGs__c){ ch.Volume_New__c = Trigger.new[i].Annual_KGs__c; ch.Volume_Old__c = Trigger.old[i].Annual_KGs__c; } CPPs.add(ch); } insert CPPs; } } else if (Trigger.isDelete){ for (Integer i = 0; i < Trigger.old.size(); i++) { CPP_Change_History__c[] doomedCPP = [select Id,Name from CPP_Change_History__c where CPP__C = : Trigger.old[i].id]; Database.DeleteResult[] DR_Dels = Database.delete(doomedCPP); } } }

 

Thanks,

Jina

Hi,

I have Person Accounts enabled in my org and I would like to have two different tabs, one for Business Account and one for Person Account. Is it possible to have separe tabs on the basis of record types. If yes, how do I achieve this?

Thanks,
Jina
Hi,

Is it possible to have Custom Tabs for VisualForce pages without associating it through a Custom Object?

Thanks,
Jina
Hi,

I have a Visual Force page which I am rendering as a pdf. I want to add page breaks to the pdf file because if the page is longer than 1 page it just splits up the page wherever it runs over. Is there any way I can control this?

Thanks
Jina
Hi,

I have a formula field named Contract End Date and the value of this field should be calucated based on Contract Start Date and the Contract Duration. Contract Start Date is of type Date and Contract Duration is the number of months. Id I just add both the fields it considers Contract Duration as number of days instead of month. How do I achieve this?

Thanks
Jina
Hi,

I have a field which needs to editable in one scenario and read-only in another. Can I achieve this using validation rules and how? Is there any other configuration where I can set this functionality. The condition depends on the record type, for a particular record type it should be read-only and for another it should be editable.

Thanks,
Jina
Hi,
 
I am rendering a page as a 'pdf' and i have used 'renderAs' attribute of apex:page. My page needs to have some checkbox on it but in pdf form those checkboxes are not visible. When I remove the renderAs='pdf' from the code, the page comes up properly with checkbox. How do I make those checkboxes visible in pdf?
 I tried using both apex:inputCheckBox and html checkbox but none of them works.
 
Thanks
Jina
Hi,

I had implemeted an onchange functionality on a apex:inputField textbox, it worked perfectly fine in Firefox but is not working in IE version 6.0

Here is the piece of code
Code:
<p> <span style="padding :23px;"/> Contract Duration : <span style="padding :12px;"/>
  <apex:outputPanel >
      <apex:inputField id="duration" value="{!contract.ContractTerm}"/><span style="padding:2px;"/><apex:outputLabel value="Months"/>
      <apex:actionSupport event="onchange" action="{!calEndDate}" rerender="endDt"/>
 </apex:outputPanel></p>
  <p> <span style="padding :21px;"/> Contract End Date       :<span style="padding :14px;"/> <apex:outputField id="endDt" value="{!contract.END_DT__c}"/></p>

Controller
 /* This method calculates the End Date depending on the Contract Effective Date 
     and Contract Duration */
    public PageReference calEndDate() 
    {
        Date dat = getContract().StartDate;
        Integer months = getContract().ContractTerm;  
        if(dat != null && months != null)
        {
            contract.END_DT__c = dat.addMonths(months);
           
        }
        
        return null;
    }

Can anyone please help me in solving this?
 Thanks
Jina

Hi

I have written this following piece of code for invoking controller method from Javascript but it does not work. I am not sure what I am missing in it,
Code:
<apex:outputPanel rendered="{!contractSummary}">
            <p><span style="padding:100px;"></span><apex:commandButton action="{!viewContractSummary}" value="View Contract Summary" styleClass="btn"/>
            <span style="padding:5px;"/><apex:commandButton value="Remove Term" onclick="validateRemove()"></apex:commandButton></p>
              <apex:actionFunction name="removeContractTerms" action="{!removeContractTerms}"></apex:actionFunction>
            <script>
                function validateRemove()
                {
                    var answer = confirm("Would you like to remove this Term from the Contract—")
                    if(answer)
                    {
                      var contractTermsId = document.getElementById('{!$Component.contractTermsId}')
                      removeContractTerms()
                    
                    }
                    else
                    {
                        alert("No"+contractTermsId)
                    }
                
                }
            </script>
       </apex:outputPanel>


Controller
 public PageReference removeContractTerms()
       {     
           delete contract_terms;
           return viewContractSummary();
           
       
       }  

  /* This method takes the user to the contract summary page */
       public PageReference viewContractSummary()
       {
        
            PageReference contSumPr = Page.contract_summary;
            contSumPr.getParameters().put('contractId', System.currentPageReference().getParameters().get('contractId'));
            contSumPr.setredirect(true);
            return contSumPr;
        
       }

 I tried both ways to call the Controller method - using the apex:actionFunction Name directly and also by using setTimeout(removeContractTerms,1000)

Can  anyone please look into this?

Thanks
Jina

Hi,

I developed a wizard with VisualForce pages and everything was working perfectly fine till yesterday and today I find that most of my logic is falling and this is one thing that I noticed -

Since I am using the rendered attribute to hide and display sections depending on different condition, I need the Boolean flag in various methods of my controller to either true or false. In methods where I have set the flags and suppose that method does not return a Boolean, the logic is not working.
 
Say for example in Wizard Step 2
 
public Contract getContract()
    {
         Id contractId = System.currentPageReference().getParameters().get('Id');
         if(contract == null)
         {
             if(contractId == null)
             {
                 contract = new Contract();
             }
             else if(contractId != null)
             {
                contract = [select id, AccountId, StartDate, END_DT__c, ContractTerm, ADV_NOTICE__c,CRT_COM__c from Contract
                    where id = :contractId];
             }
        }
       
        return contract;
        //setButtonFlags();
    }
 In the above method getContract() I was calling the below method setButtonFlags() to set the various flags. As getContract() was the first method being called from the Controller by the page I was doing the initialization here but since  getContract() method does not return a Boolean the values were not getting set.
 
 
  /* Set the contractSummary and continue Button flags */
    public void setButtonFlags()
    {
          String contractSum = System.currentPageReference().getParameters().get('contractSum');
         if(contractSum != null && contractSum.equals('true'))
         {
             setContinueButton(false);
             setContractSummary(true);
        
         }
         else
         {
        
             setContinueButton(true);
             setContractSummary(false);
         }
       
   
    }
 
Then I called this method from the getContinueButton() and the code started working as this method returns Boolean.
 /* This is the getter method for continueButton flag */
    public Boolean getContinueButton()
    {
        setButtonFlags();
        return this.continueButton;
    }
 
This was just a simple example, I have noticed the same behaviour in all the other pages. I was wondering what went wrong with all the pages that were working perfectly fine till yesterday. I don't know whether this is bug which came out while solving something else or a newly introduced restriction.

Can anyone please let me know what is the issue?

Thanks
Jina

Hi,

I have a VisualForce page which I am opening it on click of a Custom Button on the Contract Object. I want to open this page in a new window without the address bar. I tried all the following options but it does not work-

1) Opening using JavaScript by configuring it in 'Edit Contract Custom Button' - window.open('apex/Wizard_Step1a?id={!Account.Id}','scrollbars=no,resizable=no,status=no,toolbar=no,menubar=no')
2) window.open('apex/Wizard_Step1a?id={!Account.Id}','_blank')
3) By giving the option 'Display in existing window without header and sidebar' and specifying the URL of the page as '/apex/Wizard_Step1a?id={!Account.Id}'

Can anyone please help me solve this issue?

Thanks,
Jina
Hi,

I want add "Back' button functionality on my pages and the same pages are rendered from lot of places. As javascript:history.back() 
does not work in ViaualForce, is there any other way to acjieve this?

Thanks
Jina
Hi,

I have two picklist REGION and TERRITORY and the TERRITORY picklist values are dependent on REGION. I have used the following link to make my depending picklist http://wiki.apexdevnet.com/index.php/Extended_Functionality_of_Visualforce_-_Part_2 but the refresh happens only once. The second time I change my REGION value the TERRITORY does not get refreshed.

Here is  the piece of code
Code:
    <apex:pageBlock title="Section 2" rendered="{!showSecondSection}">
                        <p>To what geography does this rate apply— </p>
                        Region: <span style="padding:10px;"/>
                           <apex:actionFunction action="{!refreshPage}" name="refreshPage"/>
                         <apex:selectList value="{!contractTerms.REGION__c}" id="region" size="1">
                              <apex:selectOptions value="{!regionList}"/>
                              <apex:actionSupport event="onchange" rerender="territory"/>
                           
                         </apex:selectList>
                        
                        <p> Territory: <span style="padding:10px;"/>
                         <apex:selectList value="{!contractTerms.TERRITORY__c}" multiselect="true" id="territory" disabled="{!ISNULL(contractTerms.REGION__c)}">
                            <apex:selectOptions value="{!territories}"/>
                        </apex:selectList><p/>
                       <!-- <apex:inputField id="territory" value="{!contractTerms.TERRITORY__c}"/> --></p>
                        <p><span style="padding:10px;"/><apex:commandButton action="{!showSection3}" value="Continue" styleClass="btn"></apex:commandButton></p><br/>
                </apex:pageBlock>


Controller

 
    public List<SelectOption> getTerritories()
    {
        REGION__c region = null;
        List<REGION_TERRITORY__c> territoryList = new List<REGION_TERRITORY__c>();
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('','--None--'));
    
       if(contract_terms.REGION__c != null)
        {
           
            region = [select id, Name from REGION__c where Id =:contract_terms.REGION__c];
            territoryList = [select id, Name from REGION_TERRITORY__c where Region__c=:region.Id];
        }
          
        for(REGION_TERRITORY__c territory: territoryList )
        {
        
             options.add(new SelectOption(territory.Id,territory.Name));
        }
       
        return options ;
    
    }
    public List<SelectOption> getRegionList()
    {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('','--None--'));
        List<REGION__c> regionList = [select id, Name from REGION__c];
        
        for( REGION__c region:regionList)
        {
               options.add(new SelectOption(region.Id,region.Name));
       
        }
        return options;
    
    }
   


Can anyone please help me ?

Thanks
Jina
 

Hi,

I want to use the same inputField name more than once in the same page but the second data does not get saved although I am creating two different records. Suppose I have a custom object named Contract_Terms__c and I have a one to many relationship with another object called Term_Dates__c. So in my page I have two options - 'Enter Payment Date'  and 'Enter Cash Date', both with inputField name as term_dates.Term_Date__c. But the options creates two different records with differnt Term Type. If it is Payment Date it stores as 'Payment' and if it is 'Cash' it should store as 'cash' along with the date entered in the inputField. The record gets properly saved but the in the second record I am unable to save the date.

Here is the part of that code :
Code:
 <p>Payment Dates: <span style="padding:2px;"/> <apex:inputField id="term" 
value="{!termDates.Date__c}"/>
<span style="padding:10px;"/><apex:CommandButton action="{!addTermDates}" value="Add">
</apex:CommandButton></p><br/> <p>Enter Cash Out Decision Date(s):<span style="padding:2px;"/> <apex:inputField id="term"
value="{!termDates.Date__c}"/> <span style="padding:5px;"/><apex:CommandButton action="{!addTermDatesCash}" value="Add">
</apex:CommandButton></p>

 This is the same problem I am facing if I use the same field name once with apex:inputField and once with apex:outputField. This I need it in a scenario where depending on some condition once I need to make the field editable and once read-only.

Can anyone please suggest me how to go about this problem?

Regards,
Jina

Hi,

I have a formula field named Contract End Date and the value of this field should be calucated based on Contract Start Date and the Contract Duration. Contract Start Date is of type Date and Contract Duration is the number of months. Id I just add both the fields it considers Contract Duration as number of days instead of month. How do I achieve this?

Thanks
Jina

Hi,

 

I am getting a apex heap size error in my batch apex class. - System.LimitException: Apex heap size too large: 6030143.

The records that needs to be processed are in the range of 10k to 50K. I think it is because of the map that I am using in my code.

 This is how my code looks like

global class CreatePortfolioReport implements Database.Batchable<sObject>, Database.Stateful{
	public String query;
	global String email;

	Map<String, Purchase_Sales_Report__c[]> purchaseMap = new Map<String, Purchase_Sales_Report__c[]>();
	Map<String, Purchase_Sales_Report__c[]> salesMap = new Map<String, Purchase_Sales_Report__c[]>();
	
	
	global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<sObject> scope){
    	 for(sObject s: scope){
    	 	Purchase_Sales_Report__c ps = (Purchase_Sales_Report__c)s;
    	 	if(ps.Transaction__c != null){
	    	 	if(ps.Transaction__c.equals('Purchase')){
		    	 	if(!purchaseMap.isEmpty() && purchaseMap.containsKey(ps.Unique_Name__c)){
		    	 		purchaseMap.get(ps.Unique_Name__c).add(ps);
		    	 	}
		    	 	else{
		    	 		List<Purchase_Sales_Report__c> newList = new List<Purchase_Sales_Report__c>();
		    	 		newList.add(ps);
		    	 		purchaseMap.put(ps.Unique_Name__c, newList);
		    	 	}
	    	   }
	    	   else if(ps.Transaction__c.equals('Sales')){
	    	   		if(!salesMap.isEmpty() && salesMap.containsKey(ps.Unique_Name__c)){
		    	 		salesMap.get(ps.Unique_Name__c).add(ps);
		    	 	}
		    	 	else{
		    	 		List<Purchase_Sales_Report__c> newList = new List<Purchase_Sales_Report__c>();
		    	 		newList.add(ps);
		    	 		salesMap.put(ps.Unique_Name__c, newList);
		    	 	}
	    	   }
    	 	}
    	 } 
    	 System.debug('Purchase Map size'+purchaseMap.size());
    	 System.debug('Sales Map size'+salesMap.size());
    }
    
    global void finish(Database.BatchableContext BC){
    	Map<String, Double> salesUnits = new Map<String, Double>();
    	Map<String, Double> purchaseUnits = new Map<String, Double>();
    	Map<String, Portfolio_Report__c> portfolioMap = new Map<String, Portfolio_Report__c>();
    	List<Temp_Purchase_Report__c> purchaseList = new List<Temp_Purchase_Report__c>();
    	for(String uniqueName: salesMap.keySet()){
  			Double units = 0;
  			Double purchaseAmount = 0;
  			for(Purchase_Sales_Report__c ps:salesMap.get(uniqueName)){
  				
  				if(ps.Units__c != null){
  					units += ps.Units__c;
  				}
  			}
  			salesUnits.put(uniqueName, units);
  		}
  		System.debug('Sales Map'+salesMap.size());
  		for(String uniqueName: purchaseMap.keySet()){
  			
  	        Double units;
  			if(salesUnits.containsKey(uniqueName)){
  				units = Math.abs(salesUnits.get(uniqueName));
  			}
  			Double pUnits = 0;
  			Double product = 0;
  			Double portUnits = 0;
  			Double portAmount = 0;
  			Double divReinvAmount = 0;
  			Double divAmount = 0;
  			Double stpAmount = 0;
  			Boolean entityFlag = true;
  			Id entity;
  			String folio;
  			String assetClass;
  			String schemeName;
  			for(Purchase_Sales_Report__c ps:purchaseMap.get(uniqueName)){
  				
  				if(units != null && pUnits != units){
  					if(ps.Units__c != null){
  						pUnits += ps.Units__c;
  					}
  					
  				}
  				else{
  					
  					if(ps.Units__c != null){
  						portUnits += ps.Units__c;
  					}
  					if(ps.Amount__c != null && ps.Type__c != null){
  						
  						if(ps.Type__c.equalsIgnoreCase('NOR') || ps.Type__c.equalsIgnoreCase('SIP')){
  							portAmount += ps.Amount__c;
  						}
  						else if(ps.Type__c.equalsIgnoreCase('DIR')){
  							divReinvAmount += ps.Amount__c;
  						}
  						else if(ps.Type__c.equalsIgnoreCase('STI') || ps.Type__c.equalsIgnoreCase('SWI')){
  							stpAmount += ps.Amount__c;
  						}
  						else if(ps.Type__c.equalsIgnoreCase('DVP')){
  							divAmount += ps.Amount__c;
  						}
  					}
  					if(ps.Product__c != null){
  						product += ps.Product__c;
  					}
  					if(entityFlag){
	  					entity = ps.Entity__c;
	  					folio = ps.Folio_Number__c;
	  					assetClass = ps.Asset_Class__c;
	  					entityFlag = false;
	  					schemeName = ps.Scheme_Name__c;
  					}
  					System.debug('Create Port Units'+portUnits+'Amount'+portAmount+'Product'+product);
  				}
  				
  			}
  			if(portUnits != 0 && product != 0 && (portAmount != 0 || divAmount !=0 || divReinvAmount !=0 || divAmount != 0) ){
  				Temp_Purchase_Report__c pr = new Temp_Purchase_Report__c(Entity__c= entity, 
  																		 Folio_Number__c = folio, 
  																		 Asset_Class__c = assetClass,
  																		 UniqueName__c = uniqueName, 
  																		 Purchase_Amount__c= portAmount, 
  																		 Units_Quanitity__c = portUnits, 
  																		 Product__c = product,
  																		 Dividend_Reinvested__c = divReinvAmount,
  																		 Dividend__c = divAmount,
  																		 STP_Switch__c = stpAmount,
  																		 Scheme_Scrip_Name__c = schemeName);
  				purchaseList.add(pr);
  			}
  		}
  		System.debug('Purchase List'+purchaseList.size());
  		
  		upsert purchaseList UniqueName__c;
  		  		
  		AsyncApexJob a = [Select Id, 
                                 Status,
                                 NumberOfErrors, 
                                 JobItemsProcessed,  
                                 TotalJobItems, 
                                 CreatedBy.Email 
                                 from AsyncApexJob 
                                 where Id =:BC.getJobId()];
        // Create and send an email with the results of the batch.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {email});
        mail.setReplyTo('');
        mail.setSenderDisplayName('Batch Processing');  
        mail.setSubject('Create Portfolio Report ' + a.Status);
        mail.setPlainTextBody('The batch apex job processed ' + a.TotalJobItems +   ' batches with ' + a.NumberofErrors + ' failures.');
    
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
  		
    }
}

 As I require the map for processing the data in my finish method, I cannot think of any other option to implement it.

 

Can you please suggest me ways to avoid the error?

 

Thanks,

Jina

Hi,

 

I am getting 'Too many script statements: 50001' exception in my trigger when I do a mass insert. I have not put any DML statements inside any for loop but still I am getting the error.

 

I have a object named Goal and the trigger is on insert. I need to insert all junction object records associated with the Goal object whenever any Goal record is inserted. There are 3 junction objects associated with the Goal - Insurance/Asset/PortfolioReport.

 

Here is the piece of code

 

trigger CreateGoalAssociations on Goal__c (after insert) {
	List<GoalAssetAssociation__c> assetList = new List<GoalAssetAssociation__c>();
	List<GoalInsuranceAssociation__c> insuranceList = new List<GoalInsuranceAssociation__c>();
	List<GoalIAULIPAssociation__c> pReport = new List<GoalIAULIPAssociation__c>();
	Map<Id, Id> entityIds = new Map<Id, Id>();
	Double d= 0;
	Map<Id, Id> goalAccountMap = new Map<Id, Id>();
	List<Goal__c> goalList = new List<Goal__c>();
	
	for(Goal__c g:Trigger.new){
		goalAccountMap.put(g.Id, g.Entity__c);
		goalList.add(g);
	}
    for(Account a: [select Id,Parent_Entity__c from Account where Parent_Entity__c IN :goalAccountMap.values()]){
		entityIds.put(a.Id, a.Id);
	}
    for(Asset__c a: [select Id, Asset_Type__c from Asset__c where Entity__c IN :goalAccountMap.values()
    					OR Entity__c IN :entityIds.keySet()]){
    	
    	for(Goal__c g: goalList){
    		GoalAssetAssociation__c gA = new GoalAssetAssociation__c(Goal__c = g.Id, Asset__c = a.Id, Allocation__c = d);
    		assetList.add(gA);
    	}
    }
    
    for(Insurance__c i: [select Id, Policy_Number_or_Name__c from Insurance__c where Entity__c IN :goalAccountMap.values()
    						OR Entity__c IN :entityIds.keySet()]){
    	for(Goal__c g:goalList){
    		GoalInsuranceAssociation__c gI = new GoalInsuranceAssociation__c(Goal__c = g.Id, Insurance__c = i.Id, Allocation__c = d);
    		insuranceList.add(gI);
    	}
    	
    }
    
    for(Portfolio_Report__c p: [select Id, Portfolio_Type__c  from Portfolio_Report__c where Entity__c IN :goalAccountMap.values()
    							OR Entity__c IN :entityIds.keySet()]){
    	for(Goal__c g:goalList){
    		GoalIAULIPAssociation__c gP = new GoalIAULIPAssociation__c(Goal__c = g.Id, Portfolio_Report__c = p.Id, Allocation__c = d);
    		pReport.add(gP);
    	}
    }
     insert assetList;
     insert insuranceList;
     insert pReport;
     
}

 

Is there any way I can modify the code to avoid the errors. I have highligted the places where I am getting the error.

 

Any help on this will be very much appreciated.

 

Many Thanks,

Jina

Hi,

 

I have to prepare two financial reports on nightly basis based on the every day feed that I get into salesforce. Here are the details -

 

1. There are two objects in salesforce Purchase Report and Portfolio Report and they are linked to the Account object. Account is the master for the two objects

 

2. Every day I get a feed of the Purchase Report which details out the money invested, date etc. Each record here requires some net gain % calculation which I am currently handling it thru a batch process.

 

3. Now based on the Purchase Report, I have to prepare  the Portfolio Report records which is the summary of the Purchse Report records..

  For e.g. - Account A has 100 records in the Purchase Report,out which there are 10 unique products..i.e. 10 records each for each product.

  So my summary report should generate 10 records, summing the total amount spent for 10 records and then other calculations like net gain % etc. Also, if there is already a record for the products in Portfolio Report object, it should just update the record instead of creating a new record. This will be something like the mutual find summary report and this update should run on nightly basis.

 

4. The daily feed that I would get may have around 50 K records.

 

I am confused on what approach should I take. If I use batch process, one batch will contain only 200 records and that might not include all the records for each product. I can store the summation on a stateful class variable but then how do I handle the after processing of data.

Should I do all my post calculations of calculating gain based on the summation in the 'finsh' method and upsert the records there? Is this a good a approach or there is some other way of doing it?

 

Many Thanks,

Jina

Hi,

 

I have trigger on a custom object CPP__c on update where I am creating history records for that object if any desired value changes in the updated record. I am not using nay new id while inserting but still I get this error

 

Update_CPP_change_history: execution of AfterUpdate

caused by: System.DmlException: Insert failed. First exception on row 0 with id a04R000000141WOIAY; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

 

The trigger works fine on a single update, it only fails when I try to do a mass update through Apex Data Loader by matching the lookup fields on the CPP__c object.

 

Can someone please help me in solving this issue? I have inserting the code snippet below

 

trigger Update_CPP_change_history on CPP__c (before delete, after insert, after update) { List<CPP_Change_History__c> CPPs = new List<CPP_Change_History__c>{}; if (Trigger.isInsert) { for (CPP__c a : Trigger.new) { CPP_Change_History__c ch = new CPP_Change_History__c( Account_Name__c = a.Account__c, CPP__c = a.id, Business_Lost_Reason_New__c = a.Business_Lost_Reason__c, Business_Under_Threat_Reason_New__c = a.Business_Under_Threat_Reason__c, Business_Won_Reason_New__c = a.Business_Won_Reason__c, Change_Date__c = System.today(), Price_New__c = a.per_UOM__c, Status_New__c = a.Current_Status__c, Supplier_New__c = a.Supplier_Name__c, Producer_New__c = a.Producer_Name__c, Volume_New__c = a.Annual_KGs__c ); CPPs.add(ch); } insert CPPs; } else if (Trigger.isUpdate) { for (Integer i = 0; i < Trigger.new.size(); i++) { if ((Trigger.old[i].Supplier_Name__c != Trigger.new[i].Supplier_Name__c)|| (Trigger.old[i].Producer_Name__c != Trigger.new[i].Producer_Name__c) || (Trigger.old[i].Business_Lost_Reason__c != Trigger.new[i].Business_Lost_Reason__c) || (Trigger.old[i].Business_Under_Threat_Reason__c != Trigger.new[i].Business_Under_Threat_Reason__c)|| (Trigger.old[i].Business_Won_Reason__c != Trigger.new[i].Business_Won_Reason__c) || (Trigger.old[i].per_UOM__c != Trigger.new[i].per_UOM__c) || (Trigger.old[i].Current_Status__c != Trigger.new[i].Current_Status__c)|| (Trigger.old[i].Annual_KGs__c != Trigger.new[i].Annual_KGs__c) ) { //Creat CPP History only if certain fields change CPP_Change_History__c ch = new CPP_Change_History__c( CPP__c = Trigger.new[i].id, Change_Date__c = System.today(), Account_Name__c = Trigger.new[i].Account__c); if(Trigger.old[i].Supplier_Name__c != Trigger.new[i].Supplier_Name__c){ ch.Supplier_New__c = Trigger.new[i].Supplier_Name__c; ch.Supplier_Old__c = Trigger.old[i].Supplier_Name__c; } if(Trigger.old[i].Producer_Name__c != Trigger.new[i].Producer_Name__c){ ch.Producer_New__c = Trigger.new[i].Producer_Name__c; ch.Producer_Old__c = Trigger.old[i].Producer_Name__c; } if(Trigger.old[i].Business_Lost_Reason__c != Trigger.new[i].Business_Lost_Reason__c){ ch.Business_Lost_Reason_New__c = Trigger.new[i].Business_Lost_Reason__c; ch.Business_Lost_Reason_Old__c = Trigger.old[i].Business_Lost_Reason__c; } if(Trigger.old[i].Business_Under_Threat_Reason__c != Trigger.new[i].Business_Under_Threat_Reason__c){ ch.Business_Under_Threat_Reason_New__c = Trigger.new[i].Business_Under_Threat_Reason__c; ch.Business_Under_Threat_Reason_Old__c = Trigger.old[i].Business_Under_Threat_Reason__c; } if(Trigger.old[i].Business_Won_Reason__c != Trigger.new[i].Business_Won_Reason__c){ ch.Business_Won_Reason_New__c = Trigger.new[i].Business_Won_Reason__c; ch.Business_Won_Reason_Old__c = Trigger.old[i].Business_Won_Reason__c; } if(Trigger.old[i].per_UOM__c != Trigger.new[i].per_UOM__c){ ch.Price_New__c = Trigger.new[i].per_UOM__c; ch.Price_Old__c = Trigger.old[i].per_UOM__c; } if(Trigger.old[i].Current_Status__c != Trigger.new[i].Current_Status__c){ ch.Status_New__c = Trigger.new[i].Current_Status__c; ch.Status_Old__c = Trigger.old[i].Current_Status__c; } if(Trigger.old[i].Annual_KGs__c != Trigger.new[i].Annual_KGs__c){ ch.Volume_New__c = Trigger.new[i].Annual_KGs__c; ch.Volume_Old__c = Trigger.old[i].Annual_KGs__c; } CPPs.add(ch); } insert CPPs; } } else if (Trigger.isDelete){ for (Integer i = 0; i < Trigger.old.size(); i++) { CPP_Change_History__c[] doomedCPP = [select Id,Name from CPP_Change_History__c where CPP__C = : Trigger.old[i].id]; Database.DeleteResult[] DR_Dels = Database.delete(doomedCPP); } } }

 

Thanks,

Jina

Hi,

I have a Visual Force page which I am rendering as a pdf. I want to add page breaks to the pdf file because if the page is longer than 1 page it just splits up the page wherever it runs over. Is there any way I can control this?

Thanks
Jina
Hi,
 
I am rendering a page as a 'pdf' and i have used 'renderAs' attribute of apex:page. My page needs to have some checkbox on it but in pdf form those checkboxes are not visible. When I remove the renderAs='pdf' from the code, the page comes up properly with checkbox. How do I make those checkboxes visible in pdf?
 I tried using both apex:inputCheckBox and html checkbox but none of them works.
 
Thanks
Jina
Hi,

I had implemeted an onchange functionality on a apex:inputField textbox, it worked perfectly fine in Firefox but is not working in IE version 6.0

Here is the piece of code
Code:
<p> <span style="padding :23px;"/> Contract Duration : <span style="padding :12px;"/>
  <apex:outputPanel >
      <apex:inputField id="duration" value="{!contract.ContractTerm}"/><span style="padding:2px;"/><apex:outputLabel value="Months"/>
      <apex:actionSupport event="onchange" action="{!calEndDate}" rerender="endDt"/>
 </apex:outputPanel></p>
  <p> <span style="padding :21px;"/> Contract End Date       :<span style="padding :14px;"/> <apex:outputField id="endDt" value="{!contract.END_DT__c}"/></p>

Controller
 /* This method calculates the End Date depending on the Contract Effective Date 
     and Contract Duration */
    public PageReference calEndDate() 
    {
        Date dat = getContract().StartDate;
        Integer months = getContract().ContractTerm;  
        if(dat != null && months != null)
        {
            contract.END_DT__c = dat.addMonths(months);
           
        }
        
        return null;
    }

Can anyone please help me in solving this?
 Thanks
Jina

Hi

I have written this following piece of code for invoking controller method from Javascript but it does not work. I am not sure what I am missing in it,
Code:
<apex:outputPanel rendered="{!contractSummary}">
            <p><span style="padding:100px;"></span><apex:commandButton action="{!viewContractSummary}" value="View Contract Summary" styleClass="btn"/>
            <span style="padding:5px;"/><apex:commandButton value="Remove Term" onclick="validateRemove()"></apex:commandButton></p>
              <apex:actionFunction name="removeContractTerms" action="{!removeContractTerms}"></apex:actionFunction>
            <script>
                function validateRemove()
                {
                    var answer = confirm("Would you like to remove this Term from the Contract—")
                    if(answer)
                    {
                      var contractTermsId = document.getElementById('{!$Component.contractTermsId}')
                      removeContractTerms()
                    
                    }
                    else
                    {
                        alert("No"+contractTermsId)
                    }
                
                }
            </script>
       </apex:outputPanel>


Controller
 public PageReference removeContractTerms()
       {     
           delete contract_terms;
           return viewContractSummary();
           
       
       }  

  /* This method takes the user to the contract summary page */
       public PageReference viewContractSummary()
       {
        
            PageReference contSumPr = Page.contract_summary;
            contSumPr.getParameters().put('contractId', System.currentPageReference().getParameters().get('contractId'));
            contSumPr.setredirect(true);
            return contSumPr;
        
       }

 I tried both ways to call the Controller method - using the apex:actionFunction Name directly and also by using setTimeout(removeContractTerms,1000)

Can  anyone please look into this?

Thanks
Jina

Hi,

I developed a wizard with VisualForce pages and everything was working perfectly fine till yesterday and today I find that most of my logic is falling and this is one thing that I noticed -

Since I am using the rendered attribute to hide and display sections depending on different condition, I need the Boolean flag in various methods of my controller to either true or false. In methods where I have set the flags and suppose that method does not return a Boolean, the logic is not working.
 
Say for example in Wizard Step 2
 
public Contract getContract()
    {
         Id contractId = System.currentPageReference().getParameters().get('Id');
         if(contract == null)
         {
             if(contractId == null)
             {
                 contract = new Contract();
             }
             else if(contractId != null)
             {
                contract = [select id, AccountId, StartDate, END_DT__c, ContractTerm, ADV_NOTICE__c,CRT_COM__c from Contract
                    where id = :contractId];
             }
        }
       
        return contract;
        //setButtonFlags();
    }
 In the above method getContract() I was calling the below method setButtonFlags() to set the various flags. As getContract() was the first method being called from the Controller by the page I was doing the initialization here but since  getContract() method does not return a Boolean the values were not getting set.
 
 
  /* Set the contractSummary and continue Button flags */
    public void setButtonFlags()
    {
          String contractSum = System.currentPageReference().getParameters().get('contractSum');
         if(contractSum != null && contractSum.equals('true'))
         {
             setContinueButton(false);
             setContractSummary(true);
        
         }
         else
         {
        
             setContinueButton(true);
             setContractSummary(false);
         }
       
   
    }
 
Then I called this method from the getContinueButton() and the code started working as this method returns Boolean.
 /* This is the getter method for continueButton flag */
    public Boolean getContinueButton()
    {
        setButtonFlags();
        return this.continueButton;
    }
 
This was just a simple example, I have noticed the same behaviour in all the other pages. I was wondering what went wrong with all the pages that were working perfectly fine till yesterday. I don't know whether this is bug which came out while solving something else or a newly introduced restriction.

Can anyone please let me know what is the issue?

Thanks
Jina

Hi,

I have two picklist REGION and TERRITORY and the TERRITORY picklist values are dependent on REGION. I have used the following link to make my depending picklist http://wiki.apexdevnet.com/index.php/Extended_Functionality_of_Visualforce_-_Part_2 but the refresh happens only once. The second time I change my REGION value the TERRITORY does not get refreshed.

Here is  the piece of code
Code:
    <apex:pageBlock title="Section 2" rendered="{!showSecondSection}">
                        <p>To what geography does this rate apply— </p>
                        Region: <span style="padding:10px;"/>
                           <apex:actionFunction action="{!refreshPage}" name="refreshPage"/>
                         <apex:selectList value="{!contractTerms.REGION__c}" id="region" size="1">
                              <apex:selectOptions value="{!regionList}"/>
                              <apex:actionSupport event="onchange" rerender="territory"/>
                           
                         </apex:selectList>
                        
                        <p> Territory: <span style="padding:10px;"/>
                         <apex:selectList value="{!contractTerms.TERRITORY__c}" multiselect="true" id="territory" disabled="{!ISNULL(contractTerms.REGION__c)}">
                            <apex:selectOptions value="{!territories}"/>
                        </apex:selectList><p/>
                       <!-- <apex:inputField id="territory" value="{!contractTerms.TERRITORY__c}"/> --></p>
                        <p><span style="padding:10px;"/><apex:commandButton action="{!showSection3}" value="Continue" styleClass="btn"></apex:commandButton></p><br/>
                </apex:pageBlock>


Controller

 
    public List<SelectOption> getTerritories()
    {
        REGION__c region = null;
        List<REGION_TERRITORY__c> territoryList = new List<REGION_TERRITORY__c>();
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('','--None--'));
    
       if(contract_terms.REGION__c != null)
        {
           
            region = [select id, Name from REGION__c where Id =:contract_terms.REGION__c];
            territoryList = [select id, Name from REGION_TERRITORY__c where Region__c=:region.Id];
        }
          
        for(REGION_TERRITORY__c territory: territoryList )
        {
        
             options.add(new SelectOption(territory.Id,territory.Name));
        }
       
        return options ;
    
    }
    public List<SelectOption> getRegionList()
    {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('','--None--'));
        List<REGION__c> regionList = [select id, Name from REGION__c];
        
        for( REGION__c region:regionList)
        {
               options.add(new SelectOption(region.Id,region.Name));
       
        }
        return options;
    
    }
   


Can anyone please help me ?

Thanks
Jina
 

Hi,

I have a table which is iterating through an Account List and suppose my list has no accounts, it does not display any table but displays the header of the column. I am using the apex:dataTable and headerValue attribute of apex:column. I don't want the column header to pop up when the list is emplty.How do I achieve that?

Code:
  <apex:dataTable value="{!hiROC}" var="a" id="rows">
                        <apex:column headerValue="Greater than $">
                        <apex:inputField value="{!a.Greater_Than__c}" required="false"/></apex:column>
                        <apex:column headerValue="BPS in Rate Adjustment(+/-)">
                        <apex:inputField value="{!a.BPS_in_Rate_Adjustment__c}" required="false"/></apex:column>
                  </apex:dataTable> 

 Regards,
Jina

Hi,

I have a Text Box, where I enter Date and as soon as I click on Add it gets added to the list and displays below. Now when I am trying to remove the date from the list I am unable to do it. I have used a wrapper class to set the value of the checkbox.

Here is the code - Term_Dates__c is my custom Object having a lookup relationship with Contract_Term__c and I have created a wrapper for Term_Dates__c custom object. As soon as I click on Add, I create a new Term_Dates__c and it gets added to the list but when I am tring to remove it, it is not happening. It is working in my develoiper org but not in sandbox.

I have only pasted a part of the code that is applicable -
Code:
Code:

 <apex:pageBlock title="Section 4" rendered="{!showFourthSection}">
             <p>Select Payment Frequency: <span style="padding:2px;"/> <apex:inputText id="payFreq"/></p>
             <p>Total # of Payments: <span style="padding:2px;"/><apex:inputText ></apex:inputText> </p>
             <p>Payment Dates: <span style="padding:2px;"/> <apex:inputField id="term" value="{!termDates.Date__c}"/>
                <span style="padding:10px;"/><apex:CommandButton action="{!addTermDates}" value="Add"></apex:CommandButton></p>
                <apex:pageBlockTable value="{!allTermDates}" var="a" id="rows" title="Details of Effective Date" >
                    <apex:column ><apex:inputCheckbox value="{!a.sendToExternalService}"></apex:inputCheckbox></apex:column>
                    <apex:column ><apex:inputField value="{!a.TermDates.Date__c}"/></apex:column>
                </apex:pageBlockTable>
                 <apex:commandLink action="{!removeTermDates}" value="Remove" rendered="{!listSize}"></apex:commandLink>
                <p><span style="padding:20px;"/>Are the Hi ROC rate thresholds and/or reduction/increases adjustable— </p>
                <p><span style="padding:30px;"/><apex:commandButton action="{!showSection5}" value="Yes, Continue" styleClass="btn"></apex:commandButton>
                 <span style="padding:2px;"/><apex:commandButton action="{!nextPage}" value="No, Continue" styleClass="btn"></apex:commandButton></p>
        </apex:pageBlock>

public class Wizard_Step6_Controller 
{
     CONTRACT_TERMS__c contract_terms;
     Term_Dates__c termDate = null;
     List<TermDatesWrapper> listOfTermDatesWrapper;
     List<TermDatesWrapper> selectedTermDatesWrapper = new List<TermDatesWrapper>();
     public Term_Dates__c getTermDates()
     {
         
         termDate = new Term_Dates__c();
         
         return termDate;
     
     }
     
     public PageReference addTermDates()
     {
         termDate.TERM_ID__c = getContractTerms().Id;
         termDate.Date_Type__c = 'Payment';
         insert termDate;
         System.currentPageReference().getParameters().put('term', '');
         return null;
     
     }
     public Boolean getListSize()
     {
         Boolean termSize= false;
         if(getAllTermDates().size()>0)
         {
             termSize = true;
         }
         return termSize;
     }
     
        public List<TermDatesWrapper> getAllTermDates()
        {
            listOfTermDatesWrapper = new List<TermDatesWrapper>();
            Term_Dates__c[] allTermDates = [select id, Date__c from Term_Dates__c where TERM_ID__c =:contract_terms.Id];
            for(Term_Dates__c l : allTermDates)
            {
                TermDatesWrapper wrapper= new TermDatesWrapper(l);
                listOfTermDatesWrapper.add(wrapper);
            }
            return listOfTermDatesWrapper;
        }
        
        public List<TermDatesWrapper> getAllSelectedTermDatesWrappers()
        
        {
            return selectedTermDatesWrapper;
        }
        
        public PageReference removeTermDates()
        {
            for(TermDatesWrapper lw : listOfTermDatesWrapper)
            {
               
                if(lw.getSendToExternalService())
                {
                    selectedTermDatesWrapper.add(lw);
                    delete lw.getTermDates();
                }
                
            }
        
            return null;
        }
}



public class TermDatesWrapper {
      private final Term_Dates__c delegate;
      private boolean sendToExternalService = false;

      public TermDatesWrapper (Term_Dates__c delegate) {
        this.delegate = delegate;
      }
   
      public Term_Dates__c getTermDates() {
        return delegate;
      }
   
      public void setSendToExternalService(boolean sendToExternalService) {
        this.sendToExternalService = sendToExternalService;
      }
   
      public boolean getSendToExternalService() {
        return sendToExternalService;
      }
   
   
    }
Please help...
Hi,

Is there any way to add a help text/message beside a textbox or a inputField just like the way we have when we create any custom field through the 'Setup-Create-Objects-Any Custom Object-new Custom field' option?
Hi, I have a input text box and a button 'Add' beside the text box. As soon as I enter anything in the textbox and click on Add it should get displayed as a list below the textbox. First time I enter a value only 1 value will appear below the text box, second time I enter 2 values will appear and so on.

Logic: I have used an Array List of String and as soon as I click on 'Add' button, the add the value in the textbox to the arraylist and in my page I iterate through the List to display the values in the table. I also have a checkbox next to the value in the table. I am not being able to get any of the values. Neither the checkbox nor any entered value is visible in the table. Also how do I get to know which checkbox gets selected once I have them in the table. Here is the piece of code
Code:
<apex:page controller="Wizard_Step4c_Controller">
<apex:form >
    <apex:pageBlock title="Section 1">
        <p> Is the EDC Rate adjustable— </p>
        <p> <apex:commandButton action="{!showSection2}" value="Yes" styleClass="btn"></apex:commandButton>
        <apex:commandButton action="{!nextPage}" value="No" styleClass="btn"></apex:commandButton></p>
    </apex:pageBlock>
    <apex:pageBlock title="Section 2" rendered="{!showSecondSection}">
        <p>Enter criteria for EDC rate adjustment : </p>
        <p><apex:inputTextArea style="height:50px;width:200px;overflow-y:scroll" id="rateCriteria"></apex:inputTextArea> </p><br/>
        <p>Enter effective date(s) for EDC rate adjustment :
        <apex:inputText id="effectDates"></apex:inputText><span style="padding:10px;"/>
         <apex:commandButton action="{!addDates}" value="Add" styleClass="btn"></apex:commandButton></p> 
         <apex:dataTable value="{!dates}" var="effDate" width="50%" rows="5" rendered="true">
               <apex:column>
                  <apex:inputCheckbox id="checkb"></apex:inputCheckbox>
            </apex:column>
            <apex:column>
              {!effDate}
            </apex:column>
          </apex:dataTable>
        <p><apex:commandButton action="{!nextPage}" value="Continue" styleClass="btn"></apex:commandButton></p>
    </apex:pageBlock>
 </apex:form>
</apex:page>

public class Wizard_Step4c_Controller 
{
    Boolean secondSection = false;
    CONTRACT_TERMS__c contract_terms= null;
    Boolean showSection = false;
    List<String> dates = new List<String>();

    public Boolean getShowSecondSection() {
        return this.secondSection ;
    }
    
    public void setSecondSection(Boolean secondSection)
    {
            this.secondSection= secondSection;
    }


    public PageReference nextPage() 
    {
        if(getShowSecondSection() == true)
        {
            
                update contract_terms;
           
        }
        PageReference pr= Page.Wizard_Step4d;
        pr.getParameters().put('contractTermsId', System.currentPageReference().getParameters().get('contractTermsId'));
        pr.getParameters().put('contractId', System.currentPageReference().getParameters().get('contractId'));
        pr.getParameters().put('questNum', System.currentPageReference().getParameters().get('questNum'));
        pr.setredirect(true);
        return pr;
    }


    public PageReference showSection2() {
        setSecondSection(true);
        return null;
    }
    
    public CONTRACT_TERMS__c getContractTerms()
    {
        Id contractTermsId= System.currentPageReference().getParameters().get('contractTermsId');
        if(contractTermsId != null)
        {
            contract_terms = [select id,ADJ_RT_CRITERIA__c from CONTRACT_TERMS__c where id=:contractTermsId];
        }
        return contract_terms;
    }
    
    public pageReference addDates()
    {
        String newDate = System.currentPageReference().getParameters().get('effectDates');
        setShowTable(true);
        dates.add(newDate);
        return null;
    
    }
    
    public List<String> getDates()
    {
    
        return this.dates;
    }
    
    public void setShowTable(Boolean showSection)
    {
        this.showSection = showSection;
    }
    
     public Boolean getShowTable()
    {
        return this.showSection;
    }
}
 
Can anyone please help me resolve this issue?

Thanks, Jina
Hi,

I have to create a back button which will do a browser back operation but somehow the onclick="javascript&colonhistory.back();" is not working for the button. Here is the piece of code below.

Code:
<apex:facet name="footer">
       <apex:commandButton  onclick="javascript&colonhistory.back();" value="Back"/>
</apex:facet>

 Can you anyone please suggest me how to do this?

Regards,
Jina