• vishal@force
  • 1863 Points
  • Member since 2011

  • Chatter
  • 69
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 7
  • 426



what is trigger handler pattern  in salesforce  and could u give some examples on it.




Hi all, I wrote a trigger and test class bit it's only hitting 50% can anyone help with what's missing?




trigger changeLeadOwner on Lead (before insert, before update) {
 	      id ProfileId = userinfo.getProfileId();
 	      profile StandardProfile = [select id from profile where name='Admin User'];
 	      if (ProfileId == StandardProfile.Id) {
 	        // no bulk processing; will only run from the UI
 	          if (Trigger.new.size() == 1) {
 	              for (Lead lead :trigger.new) {
 	                  lead.Ownerid =lead.Phone_Lead_Owner__c;

 Here's the Class:


public class TestchangeLeadOwner {
     // Methods for testing 
   @isTest static void test1() {
         profile StandardProfile = [select id from profile where name='Admin User'];
         User usrObj = [select id from User LIMIT 1];

         Lead ld = new Lead(Lastname='testLead', Company='companyTest' );

         ld.Phone_Lead_Owner__c = usrObj.id;

         insert ld;

         update ld;



 Here's that the test result is highlighting red


if (Trigger.new.size() == 1) {  10    for (Lead lead :trigger.new) {  11    lead.Ownerid =lead.Phone_Lead_Owner__c;



Any help and tips would be greatly appreciated.

  for(Task a : Trigger.old){
              if(a.OwnerId != UserInfo.getUserId()  && ProfileId  != '00e00000006qrDIAAY' )

                      a.addError('You are not authorised to delete this task!');


I have been working for the last 3 days on a couple of trigger and test classes in the Sandbox. Which I got 100% and was working all fine in Sandbox. Now when I move it too production it doesn't work. 
I did a refresh of the sandbox before moving it so the fields / val rules are the same. 
I have turned on the debug logs (I am no expert) but can not even see them firing. 
I tried to edit the code in sandbox by just removing white space in case thats why it wasn't working and now it is isn't working in the sandbox either. 
Even when I put the original code back. 

Can any help?


trigger cloneElecAMsignOff on Electricity_Meter__c (before update) {

     List<Electricity_Meter__c> myList = new List<Electricity_Meter__c>();

     for(Electricity_Meter__c a: trigger.new) {

        // insert Elec meter if Deal Done
        if (
        a.Account_Manager_Sign_Off_Date_Time__c != Null &&
        a.Clone_Date_Time_Stamp__c == Null && 
        a.Deal_Done_Not__c == 'Deal Done (Existing client / Existing meter)' ||
        a.Deal_Done_Not__c == 'Deal Done (New Meter, New Client)' || 
        a.Deal_Done_Not__c == 'Deal Done (New Meter, Exisiting Client)')) {
        Electricity_Meter__c b = new Electricity_Meter__c();                
        b.Name = a.Name; 
        b.Site_name__c = a.Site_name__c;
        b.Contract_arranged_under_the_name_of__c = a.Winning_Contract_Arranged_Under_Name_of__c;
        b.Account__c = a.Account__c; 
        b.Linked_Basket__c = a.Linked_Basket__c;
        b.Linked_Monitor_Line__c = a.Linked_Monitor_Line__c;
        b.Current_Supplier__c = a.Winning_Supplier__c;
        b.Previous_Supplier__c = a.Current_Supplier__c;
        b.Meter_Status__c = '(2) Active (Not yet live)';
        b.COT_Disc_Deenerg_Date__c = a.COT_Disc_Deenerg_Date__c;       
        b.Auto_Manual_Term__c = a.Auto_Manual_Term__c;
        b.Linked_Affiliate_1__c = a.Linked_Affiliate_1__c;    
        b.Aff_1_Profit_Split__c = a.Aff_1_Profit_Split__c;
        b.Linked_Affiliate_2__c = a.Linked_Affiliate_2__c;    
        b.Aff_2_Profit_Split__c = a.Aff_2_Profit_Split__c;        
        b.Linked_Affiliate_3__c = a.Linked_Affiliate_3__c;    
        b.Aff_3_Profit_Split__c = a.Aff_3_Profit_Split__c;
        b.Site_Address_New__c = a.Site_Address_New__c;
        b.Site_Postcode__c = a.Site_Postcode__c;
        b.Co_Reg_FULL_Partnership_LLP_Sole_Trader__c = a.Co_Reg_FULL_Partnership_LLP_Sole_Trader__c;
        b.Billing_Address_New__c = a.Billing_Address_New__c;
        b.Billing_Postcode__c = a.Billing_Postcode__c;
        b.Number_of_employees__c = a.Number_of_employees__c;
        b.Annual_turnover_Euros__c = a.Annual_turnover_Euros__c;
        b.Profile_Class__c = a.Profile_Class__c;
        b.MTC_LLF__c = a.MTC_LLF__c;
        b.Meter_Details__c = a.Meter_Details__c; 
        b.MOP_CED__c = a.MOP_CED__c;
        b.Voltage_HV_LV_LVS__c = a.Voltage_HV_LV_LVS__c;
        b.Contract_start_date__c = a.Winning_Contract_Start_Date__c;
        b.Contract_expiry__c = a.Winning_Contract_End_Date__c;
        b.Payment_Method__c = a.Payment_Method__c;
        b.DD_Type__c = a.DD_Type__c;
        b.VAT__c = a.VAT__c;
        b.Monthly_Quarterly_Billing__c = a.Monthly_Quarterly_Billing__c;
        b.Copy_of_the_bills__c = a.Copy_of_the_bills__c;
        b.AQ__c = a.Winning_Supply_AQ__c;
        b.Total_KVA__c = a.Total_KVA__c; 
        b.Commission_p__c = a.Winning_Commision_p_kwh__c;
        b.Commission_per_year__c = a.Winning_Commission_year__c;
        b.Commission_Percent__c = a.Winning_Commission_Contract__c;  

        // insert Elec meter if Deal Not Done
        else if (a.Account_Manager_Sign_Off_Date_Time__c != Null && 
        a.Clone_Date_Time_Stamp__c == Null && 
        a.Deal_Done_Not__c == 'Deal not done / Not responding - Client retained' ||
        a.Deal_Done_Not__c == 'Deal not done / Not responding - Client lost' ||
        a.Deal_Done_Not__c == 'Deal not done / Went direct with supplier - Client retained' ||
        a.Deal_Done_Not__c == 'Deal not done / Went direct with supplier - Client lost' ||
        a.Deal_Done_Not__c == 'Deal not done / Went with another consultant - Client retained' ||
        a.Deal_Done_Not__c == 'Deal not done / Went with another consultant - Client lost' ||
        a.Deal_Done_Not__c == 'Deal not done / Meter removed - Client retained' ||
        a.Deal_Done_Not__c == 'Deal not done / Meter removed - Client lost')) {
        Electricity_Meter__c c = new Electricity_Meter__c();                
        c.Name = a.Name; 
        c.Site_name__c = a.Site_name__c;
        c.Contract_arranged_under_the_name_of__c = a.Winning_Contract_Arranged_Under_Name_of__c; 
        c.Account__c = a.Account__c; 
        c.Linked_Basket__c = a.Linked_Basket__c;
        c.Linked_Monitor_Line__c = a.Linked_Monitor_Line__c;
        c.Current_Supplier__c = a.Winning_Supplier__c;
        c.Previous_Supplier__c = a.Current_Supplier__c;
        c.Meter_Status__c = '(5) Active';
        c.COT_Disc_Deenerg_Date__c = a.COT_Disc_Deenerg_Date__c;        
        c.Auto_Manual_Term__c = a.Auto_Manual_Term__c;
        c.Linked_Affiliate_1__c = a.Linked_Affiliate_1__c;    
        c.Aff_1_Profit_Split__c = a.Aff_1_Profit_Split__c;
        c.Linked_Affiliate_2__c = a.Linked_Affiliate_2__c;    
        c.Aff_2_Profit_Split__c = a.Aff_2_Profit_Split__c;        
        c.Linked_Affiliate_3__c = a.Linked_Affiliate_3__c;    
        c.Aff_3_Profit_Split__c = a.Aff_3_Profit_Split__c;
        c.Site_Address_New__c = a.Site_Address_New__c;
        c.Site_Postcode__c = a.Site_Postcode__c;
        c.Co_Reg_FULL_Partnership_LLP_Sole_Trader__c = a.Co_Reg_FULL_Partnership_LLP_Sole_Trader__c;
        c.Billing_Address_New__c = a.Billing_Address_New__c;
        c.Billing_Postcode__c = a.Billing_Postcode__c;
        c.Number_of_employees__c = a.Number_of_employees__c;
        c.Annual_turnover_Euros__c = a.Annual_turnover_Euros__c;
        c.Profile_Class__c = a.Profile_Class__c;
        c.MTC_LLF__c = a.MTC_LLF__c;
        c.Meter_Details__c = a.Meter_Details__c; 
        c.MOP_CED__c = a.MOP_CED__c;
        c.Voltage_HV_LV_LVS__c = a.Voltage_HV_LV_LVS__c;
        c.Contract_start_date__c = a.Winning_Contract_Start_Date__c;
        c.Contract_expiry__c = a.Winning_Contract_End_Date__c;
        c.Payment_Method__c = a.Payment_Method__c;
        c.DD_Type__c = a.DD_Type__c;
        c.VAT__c = a.VAT__c;
        c.Monthly_Quarterly_Billing__c = a.Monthly_Quarterly_Billing__c;
        c.Copy_of_the_bills__c = a.Copy_of_the_bills__c;
        c.AQ__c = a.Winning_Supply_AQ__c;
        c.Total_KVA__c = a.Total_KVA__c; 
        c.Commission_p__c = a.Winning_Commision_p_kwh__c;
        c.Commission_per_year__c = a.Winning_Commission_year__c;
        c.Commission_Percent__c = a.Winning_Commission_Contract__c;




Hi, I'm fairly new to Triggers and am hoping someone can give me a bit of direction.


I want a custom field "Record_Mode__c" on Child Object B to be updated to value "Edit" when Parent Object A's custom field "Status__c" is updated to "Open". Basically, any time the parent record's status changes, I want the child record's Record Mode field to be updated accordingly.


The Record Mode change will then drive workflow that will flip record types and page layouts. I prefer to use out of the box solutions, but I cannot use cross object workflows as there is no master detail relationship between Parent Object A and Child Object B.


Any assistance with code or alternate solutions are much appreciated! 



this id a date field type.


I need to get month from the above date in trigger code.


Eg: c.Contract_Start_Date__c =13/12/2012


then i need Month= DEC 

  • December 13, 2012
  • Like
  • 0

I'm using Apex to perform some basic XML parsing. I'm having no luck getting to any of the actual XML node names. The getLocalName()  method within the XmlStreamReader class always returns null for all nodes as I loop through them.



private class BPTCalloutTest {
private static final String XML_STR = '<document>' +
'<result>success</result>' +
'<resultcode>000000</resultcode>' +
'<note></note>' +
                                        '<item>' +
      '<quantity>1</quantity>' +
  '<fname>Bob</fname>' +
  '<lname>Tungsten</lname>' +
  '<address>23232 Fleet Street</address>' +
  '<city>Santa Clara</city>' +
  '<state>CA</state>' +
  '<zip>94105</zip>' +
  '<country>United States</country>' +
  '<email>blahblahblah@blahblahblah.com</email>' +
  '<phone>4155555555</phone>' +
    '</item>' +
    static testMethod void xmlStreamReaderTest() {
        XmlStreamReader reader = new XmlStreamReader(XML_STR);
        Opportunity[] opptyList = BPTCallout.parseXML(reader);
        System.assert(opptyList != null);



public with sharing class BPTCallout {
    public BPTCallout() {}

    public static Opportunity[] parseXML(XmlStreamReader reader) {
        Opportunity[] oppList = new List<Opportunity>();

        if (reader != null) {
            while (reader.hasNext()) {
            	System.debug('$$$ reader.getEventType(): ' + reader.getEventType());
                if (reader.getEventType() == XmlTag.END_DOCUMENT) {
                else if (reader.getEventType() == XmlTag.CHARACTERS) {
                	System.debug('$$$ reader.getLocalName(): ' + reader.getLocalName());
                	System.debug('$$$ reader.getText(): ' + reader.getText());
                	System.debug('$$$ reader.getNamespace(): ' + reader.getNamespace());
                	System.debug('$$$ reader.getlocation(): ' + reader.getlocation());
                	System.debug('$$$ reader.getprefix(): ' + reader.getprefix());
                	if (/*reader.getLocalName() == 'lname'*/ reader.getAttributeCount() == 4 && reader.getText() != null) {
	                    oppList.add(new Opportunity(Name = reader.getText()));
        System.debug('$$$ oppList: ' + oppList);
        return oppList;


Very basic functionality at this point. If you run this, you will see that reader.getLocalName() always returns null and so do all accompanying methods (getNameSpace, getLocation, getPrefix).


Thanks in advance.




I have a situation I need to solve.


I want to have an autoincrease number that will be increased with every new lead created in the system. This variable shouldnt be increased with every lead,just with the ones which record type is "Group".


I figured out a solution: to create a custom object that will contain this number. Then, everytime a new Group lead is created, it will fire a trigger that will access to this object take the number and increase it. But I think I might have some concurrency problems....It will be rare, but it might happen.


Do you know any other solution for this case?


Thanks a lot!



I'm fairly new to apex and only have experience with c# and VB, so apologies if this is a simpleton question.


I have a field called Feedback Email Sent Date (which intuitively is the datetime value a feedback email was sent), and I want to write a piece of code that checks for all cases where this value is 3 days or more ago. So far I have:


      Datetime daysago = now().addDays(-3);
      Case[] c = [SELECT Id, Feedback_Email_Sent_Date__c FROM Case WHERE Feedback_Email_Sent_Date__c >= daysago];

 I am currently getting an error saying daysago is an invalid token, how can I fix this?


Also, I would also like to ignore all records where the feedback sent date field is blank (meaning we haven't sent a feedback email), is there a simple way of doing this too?


Cheers for any help :)

Hi Everyone,


I think everyone is doing well.


Here is my code:


VisualForce Page:


<apex:page StandardController="Case" Extensions="ONEN_CTRL_WebToCase" action="{!submitCase}">
<apex:form >
<th>Your Name:</th>
<td><apex:inputText value="{!Case.Account.Name}"/></td>
<th>Your Email:</th>
<td><apex:inputText value="{!Case.Contact.Email}"/></td>
<td align="right">
<apex:outputLabel value="Reason for Contact" for="txtPostalCode" styleClass="label" /><br/>
<apex:selectlist value="{!Case.Description}" id="txtPostalCode" styleclass="select">
<apex:selectOptions value="{!reason4Contact}"/>
<td><apex:commandButton value="Save" action="{!save}"/></td>



Apex Code:


public class ONEN_CTRL_WebToCase1 {
Public Account Account {get; set;}
Public Contact Contact {get; set;}
Public Case cas {get; set;}
public List<SelectOption> getReason4Contact() {
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('Select a Topic','Select a Topic'));
return options;
public PageReference save() {
return null;
public PageReference submitCase() {
Map<string,string> postParameters = ApexPages.currentPage().getParameters();
String LastName = ApexPages.currentPage().getParameters().get('Last_Name');
String Email = ApexPages.currentPage().getParameters().get('Email');
Account=New Account();
Contact=New Contact();
Cas=New Case();

insert Cas;
return null;
public ONEN_CTRL_WebToCase1(ApexPages.StandardController controller) {



Here my requirement is that if url parameter email='xxx@yyy.com' and Contact.Email='xxx@yyy.com' it must fetch Account.name and Contact.Email from contact and has to insert a record in the case.




1. URL of the VFPage: \apex\VFPage?Last_Name='Anil'&Email='anil@talluri.com'

2. Contact.Email='anil@talluri.com'


3. In 2nd point, Contact.Email=Email

=> Fetch the account.name, contact.email from contact


4. Insert the record in case with the above account.name, contact.email


Please help me in implementing this. (I'm not at all satisfied with my code)



  • November 28, 2012
  • Like
  • 0

Hi Community,


I wrote a trigger on opportunity which will insert few fields on Opportunity it self grabbing the data from a contact object

Here my question is the following trigger is error free but looks to me not completly bulkified and not so efficient.


Can any body suggest the improvement and correct me if i am doing wrong.


Trigger optInsertContactData on Opportunity(after Insert){


set<Id> ids =new set<Id>();

for(opportunity op: Trigger.new){




List<opportunity> opList = new List<opportunity>();

List<Contact> cntList = new List<Contact>([Select x, y from Contact where Id IN: ids]);


opList[0].x = cntList[0].x;

opList[0].y = cntList[0].y;


Insert opList;


Thanks in advance for your precious time and suggestions.

Hi all,

I am trying to develop a trigger, but it seems I keep hitting a Null Pointer Exception and cannot figure out why.  Anyone can help take a look?


trigger AccountChildRollup2 on account (before update, before insert) {
    set<id> pid = new set<id>();
    for (account child : trigger.new){
    aggregateresult children = [select count(id) from account where parentid in: pid];
    aggregateresult livechildren = [select count(id) from account where type = 'Live' and parentid in: pid];
    integer childcount = integer.valueof(children.get('expr0'));
    integer livechildcount = integer.valueof(livechildren.get('expr0'));
    map<id,account> pmap = new map<id,account>([select id, type, go_live_date__c, count_child_accounts__c, count_live_child_accounts__c from account where id in: pid]);
    for (account child : trigger.new){
        account p = pmap.get(child.parentid);
        p.count_child_accounts__c = childcount;
        p.count_live_child_accounts__c = livechildcount;
    update pmap.values();


Error:Apex trigger AccountChildRollup2 caused an unexpected exception, contact your administrator: AccountChildRollup2: execution of BeforeUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.AccountChildRollup2: line 15, column 1 



I have a trigger on a custom object (Contract_Summary__c) that populates a custom lookup field on the associated Account record with the Contract_Summary__c record as long as it is a particular type.  I would now like to add a condition that will only overwrite the value in the lookup field on the Account if the Current_Effective_Date__c field on the new Contract_Summary__c record is greater than the Current_Effective_Date__c field on the Contract_Summary__c record that is already populated in the Account custom lookup field.  I'm guessing this is not difficult to accomplish, but I am stumped.  My code is below if anyone can help:



trigger Contract2Account on Contract_Summary__c (after insert, after update)
Map<Id,Account> oppMap = new Map<Id,Account>();
Set<id> Ids = new Set<id>();

if(trigger.isInsert || trigger.isUpdate)

for (Contract_Summary__c prgm : Trigger.new)
if((prgm.Type_of_Contract__c == 'Renewal' || prgm.Type_of_Contract__c == 'Initial MSA') && (prgm.Current_Effective_Date__c > prgm.Account_Name__r.Contract_Summary__r.Current_Effective_Date__c || prgm.Account_Name__r.Contract_Summary__c == null))

Map<id,Account> acctMap2 = new Map<id,Account>([Select Id,Name,Contract_Summary__c from Account Where Id in :Ids]);

for (Contract_Summary__c prgm2 : Trigger.new)
Account a = acctMap2.get(prgm2.Account_Name__c);
a.Contract_Summary__c = prgm2.Id;

update oppMap.values();


catch(Exception e)





  • November 27, 2012
  • Like
  • 0

Hello All, new to apex coding and running into a production issue.  Scheduled class runs fine in sandbox, deployed successfully with 100% code coverage, but now the job isn't executing in production.  Scheduled with the Schedule Apex tool in UI just as in Sandbox.  The job shows up in Scheduled Jobs but nothing happens, no errors, nothing to see in Apex Jobs.  Anyone see anything wrong with the following...


 This is the scheduler


global class AddParentCompanyScheduler implements Schedulable{
   global void execute(SchedulableContext SC) {
      AddParentCompany A = new AddParentCompany();


this is the class and method the scheduler should execute.  imnaccount is a custom object.


public  class AddParentCompany {
//If an account has a parent account, any related opportunities or imnaccounts
//should have the same parent.

//Create a list of accounts with parents and loop through each record.
  public void getParents(){
    for (List<Account> acctsWithParents: [Select a.ParentId, 
      a.Id From Account a WHERE a.ParentID != null]){
        for(Account currAcct: acctsWithParents){
    // For every account in the resulting list, pull a list of opportunities.
    //Update the opportunities with the account's parent account.        
          for(List<Opportunity> oppsWithCurrAcct : [Select o.Parent_Company__c, 
                  o.AccountId, o.Id From Opportunity o 
                  WHERE o.AccountID = :currAcct.Id]){
            for(Opportunity currOpp: oppsWithCurrAcct){
              currOpp.Parent_Company__c = currAcct.ParentId;
            Database.update (oppsWithCurrAcct);
    // For every account in the resulting list, pull a list of imnaccounts.
    //Update the imnaccounts with the account's parent account.      
          for(List<IMNAccount__c> imnWithCurrAcct : [Select i.Parent_Company__c, 
                  i.Id, i.Company__c From IMNAccount__c i
                  WHERE i.Company__c = :currAcct.Id]){
            for(IMNAccount__c currImn: imnWithCurrAcct){
              currImn.Parent_Company__c = currAcct.ParentId;
            Database.update (imnWithCurrAcct);



  • November 27, 2012
  • Like
  • 0

I am trying to use a SOSL query where the criteria will be input from a text box on a VF page. I am running into a null pointer exception and struggling to figure out what it is. It is my first time using SOSL. So, I'm hoping the issue will be easy to spot.


public with sharing class mergeMaster {

	public string searchString {get; set;}
	public List<resultWrapper> wrappedResults {get; set;}
    //fired when the Search button is clicked
    public PageReference search() {
    	List<List<SObject>> searchList = [FIND :searchString IN ALL FIELDS RETURNING CONTACT (Id, Name, Account.Name Order By Name) ];    	
    	for(Contact reCon : (List<Contact>) searchList[0]) {    		
    		resultWrapper wrCon = new resultWrapper(reCon.Id, reCon.Name, reCon.Account.Name);
    		//system.assert(false,'Results: '+wrCon);
    	return null; 
    public class resultWrapper {
        public Id contactID {get; set;}
        public String contactName {get; set;}   
        public String accountName {get; set;}
        public List<SelectOption> masterORchild {get; set;}
        public resultWrapper(ID cID, String cName, String aName) {
            contactID = cID;
            contactName = cName;
            accountName = aName;
            this.masterORchild = new List<SelectOption>{new SelectOption('The Master','The Master'),new SelectOption('Merge','Merge')};




<apex:page sidebar="false" controller="mergeMaster" standardstylesheets="false">
    <apex:sectionheader title="Merge Master" />
     <apex:form id="theform">
     <apex:pageBlock mode="edit" id="block">
     	<apex:pageBlockSection >
        	<apex:pageBlockSectionItem >            
             <apex:panelGroup >
             	<apex:inputText id="searchString" value="{!searchString}"/>
             	<apex:commandButton value="Search" action="{!search}" rerender="block" status="status"/>
        <apex:actionStatus id="status" startText="Searching... please wait..."/>
        <apex:pageBlockSection >  
			<apex:pageBlockSection title="Search Results" id="resultsBlock" columns="1">
 			<apex:pageBlockTable value="{!wrappedResults}" var="item" rendered="{!NOT(ISNULL(wrappedResults))}">
   				<apex:column value="{!item.contactName}" headerValue="Contact" width="100"/>
   				<apex:column: value="{!item.accountName}" headerValue="Account" width="200"/>          				




I would like to know how to fetch default piclist values of a field in apex class.



I need to insert 100 records at atime, and this trigger doesnt work, please help me writing bulk trigger.


trigger emailcopy on Lead (before update, before insert) {

Lead ld = Trigger.new[0];
if(ld.Contact__c!=null&& ld.RecordTypeId == '012V00000008atT') {
Contact con = [Select id,Email,AccountId,Phone,Phone_Extension__c,MobilePhone from Contact where id =: ld.Contact__c];
Account acc = [Select id,AutomationandControlProductsRegion__c from Account where id =: con.AccountId];

ld.AutomationandControlProductsRegion__c = acc.AutomationandControlProductsRegion__c;
ld.Email = con.Email;
ld.Phone = con.Phone;
ld.PhoneExtension__c = con.Phone_Extension__c;
ld.MobilePhone =con.MobilePhone;


  • November 20, 2012
  • Like
  • 0

I'm attempting to update Contacts that are associated with an opportunity via contact roles when the opportunity Demo Status (custom field) is NOT equal to Null.  (Its a picklist that starts out blank).  I've written this code so far but I'm getting stuck as to how to make the transition from Contact Role to updating the contact.  It is giving me an error of Compile Error: Illegal assignment from SOBJECT:OpportunityContactRole to SOBJECT:Contact at line 36 column 13


Any help would be greatly appreciated.





trigger OpportunityDemoContactUpdate on Opportunity (after insert, after update) {

    // map tracks records on OpportunityID

    Map<String, Opportunity> OpportunityMap = new Map<String, Opportunity>();

    for( Opportunity record : Trigger.new )
        if( record.Demo_Status__c != null)

              OpportunityMap.put( record.ID, record );            

    if( OpportunityMap.keySet().size() > 0 ) // if there are no eligible Quote records, end
 //map to keep track of the opportunity contact roles
    map<Id, OpportunityContactRole> oppycontactroles = new map<Id, OpportunityContactRole>();

    //select OpportunityContactRoles for the opportunities with contact role required

    List<OpportunityContactRole> ContactRoles = [select OpportunityID, ContactID from OpportunityContactRole where OpportunityID in :OpportunityMap.keySet() ];

    for (OpportunityContactRole ocr : ContactRoles) {
        //puts the contact roles in the map with the Opportunity ID as the key

        // update Contact Prior Demo field from the matching record
        for( Contact contact : ContactRoles)
            Contact record = oppycontactroles.get( Contact.id ); // grab the correct record from the map
            Contact.Prior_Demo__c = 1;

        // Save Prior Demo value to the database
        Database.SaveResult[] results = Database.update( ContactRoles );
        for( Database.SaveResult result : results )
if( !result.isSuccess() ) System.debug( '<< '
+ result.getErrors().size() + ' update error(s) on Contacts: ' + result.getErrors()[0].getMessage() );


I am getting an error while saving a note as i want to change the Title of the Note with Body content upto 77 alphabhets.


Error-   INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call


Here is my code:-

trigger NotesTitleBeforeInsert on Note (after insert,after update){

List<Note> allTitles = new List<Note>();
if(trigger.isInsert || trigger.isUpdate){
for(Note nT: Trigger.new){
List<Note> ntList = [select ID,Title,Body,ParentId,Parent.Id from Note where Id =:nT.Id];
String titleValue;
for(Note n1 : ntList){
titleValue = n1.Title.substring(0, 6);
Boolean TitleTest = Pattern.matches('[0-9]', titleValue);
//Pattern titlePattern = Pattern.Compile('[0-9]{10}');
//Matcher NoteTitle = titlePattern.matcher(n1.Title);

if(TitleTest == true){
n1.Title = n1.Body.substring(0, 76);
//update n1;

if(allTitles.size() > 0 ){
insert allTitles ;

I'm trying to create a shedule job that sends email alerts 2 days befor due date. But some how list task near overdue doesn't let me save. It shows problem with the last "And" part( The highlighted part). Could somebody point me out where I am going wrong?  



List<Task> tasksNearOverdue =[SELECT Id, ActivityDate, Subject FROM Task WHERE WhatId IN :requestIds AND IsClosed = false AND :Date.today().addDays(-2) >= ActivityDate ] ;

Hello all,


As per the documentation provided here (http://wiki.developerforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com), I am trying to understand how OAuth works for salesforce authentication. 


What I have done so far: (I have client id and secret from a remote app)


1. Created a Sites VF Page which has a button that redirects to the salesforce authentication page (https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=<your_client_id>&redirect_uri=<your_redirect_uri>)


2. This gives me a CODE on the redirecturi page, from here I call the  'https://login.salesforce.com/services/oauth2/token' service passing all the required params, this gives me a access_token.


3. I have a Apex REST class, this is where I am not able to proceed. When I try to hit this url, I get an error response that says "This session is not valid for use with the REST API". I am also passing the "Authorization" header in the request.


I need someone to tell me what am I doing wrong? And the implementation done so far is correct or it needs to be changed?

I have been using actionStatus on visualforce pages since a long time but never came across a scenario where the method for which I use it is a PageReference method. AJAX, as far as I understand, is for refreshing a section of a page. In Pagereference, we move to another page, so does it still support actionStatus?


I tried this on a simple visualforce page - onclick of a commandbutton I call a PageReference method with Status attribute and it shows me the status but does not redirect.


Now, if I remove the status and try clicking on it, it redirects me to the other page.

Is this the expected behaviour or am I missing something here? Please advice.


Thanks in advance,


Hello everyone,


I have a requirement where with Apex, I was generating chatter feeds and using the ParentId, I was posting it in a Chatter Group. 


Now, the users want that along with posting it in the Group, this feed should also be displayed in a custom visualforce related list on the record detail page. 


To fetch feeds related to a record, I would need the ParentId to be that of the record. This will then not allow me to post it in the group (which I'm currently doing). 


So I need to know if there's a way to post a feed in a group as well as associate it with a Record using Apex? 

Hello people,


We have a requirement where we have to send email  on submission of a form. The email should have an attachment which has dynamic content based on the record. I couldn't find any OOTB feature that will allow me to do so. But if I missed something here, please advice.


Coming to doing this using Apex, in my submit code (it's just a simple button click), I am inserting contacts and then using a visualforce page which is rendered as pdf to give me a blob which I'm then attaching to my email. The visualforce page has StandardController, so passing the id would give me record-specific data. 


However, the issue I am facing here is that when the .getContent() method is called from my code, I get an "unable to retrieve object" error. Is it that since the record has just been inserted and immediately I'm using it's standard controller?

It is the same issue here too :


Any ideas/solutions?  

Hi all,


I came across an issue today while testing on one of the projects. We are making api calls from flex, we had to modify the code for support to "Platform license" users, but I noticed that I cannot query Profile if "View setup and configuration" permission is disabled for a user.


In our case, the only reason we want to query from Profile is to get the current user's license type, giving them permission to setup area for that wouldn't be feasible.


Is there any work around? Or any other way where I can get a user's license type without a need to query his profile? Please help me, it's urgent.


This is the error I get once I disable the permission : "Invalid column "Profile" on User entity.

And this is the query I am having here :


Select Profile.UserLicenseId, ProfileId From User Where Id = userinfo.getUserId()

Hi people,


I have a requirement where I have to create API's which will then be used for creating/accessing Salesforce records. It has to be a part of a managed package. After reading a few articles, I found out that I can do this using Apex Rest API, ie, creating an endpoint and in that class defining our Get and Post methods that will be used for creating/modifying records.


I have never worked on API's before. So I want to know if this is the right approach? I am not sure because it has to be packaged.


If it is a correct approach, then how should I proceed? If I set up an endpoint, how do I test it? Pleas let me know so that I can proceed with it. Thanks in advance.

Hi force.com-geeks!


I wanted to try and implement creating REST API's using Apex REST. As per the documentation provided, I did understand the steps for it. (referred this : Creating_REST_APIs_using_Apex_REST)


Once I create an endpoint, I am unable to know how exactly should I be able to access it through some other Salesforce Org. I know it requires authentication process, but since most of the examples show configuration from a java app or a desktop app, I don't know how do I configure my Remote Access and what should be the callback url if I want to access the API class through some other salesforce dev org.


Can anyone please guide me for configuring the Remote Access and how to authenticate the destination org (where the API exists) from the source dev org.


  There is a custom object with name NSP__c When every object is either inserted or updated with values. I am firing a trigger to update 
Amount field in OpportunityLineItem Problem is value is not getting updated. I am not sure what is the issue. 

I tried creating a test field in opportunity to test this value is getting updated. Please suggest me how to fix this issue. 

trigger NSPActiveAmount on NSP__c (after insert,after update)
  List <Id> OpportunityIds = new List<Id>();

    for(NSP__c N : trigger.new)

  List <Opportunity> opiRecords = [SELECT test__c FROM Opportunity
                                             WHERE Id = :OpportunityIds];
   List <OpportunityLineItem> oliRecords = [SELECT UnitPrice FROM OpportunityLineItem
                                             WHERE OpportunityId = :OpportunityIds];
    List <NSP_Details__c>  NSPDetails = [ SELECT  Distributor_Requested_Unit_Price__c
                                          FROM NSP_Details__c
                                          WHERE NSP__c in ( SELECT ID FROM NSP__c
                                                            WHERE opportunity__c  = :OpportunityIds) ];
    for (Opportunity opp :opiRecords)
      for (OpportunityLineItem oppItem :oliRecords )
       for (NSP_Details__c NSP_Details :NSPDetails)
        opp.test__c = NSP_Details.Distributor_Requested_Unit_Price__c;
        oppItem.UnitPrice =  NSP_Details.Distributor_Requested_Unit_Price__c;                    
  Update  opiRecords;
  Update oliRecords;                          





what is trigger handler pattern  in salesforce  and could u give some examples on it.




Hi all,


Can someone please explain me List, Set and Map with simple programs as examples.


I have already gone through the Salesforce http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_list.htm and other two links for Set and Map. Unluckily I am not able to understand any thing in this as I am new to write the code.


Please help..




Hi all, I wrote a trigger and test class bit it's only hitting 50% can anyone help with what's missing?




trigger changeLeadOwner on Lead (before insert, before update) {
 	      id ProfileId = userinfo.getProfileId();
 	      profile StandardProfile = [select id from profile where name='Admin User'];
 	      if (ProfileId == StandardProfile.Id) {
 	        // no bulk processing; will only run from the UI
 	          if (Trigger.new.size() == 1) {
 	              for (Lead lead :trigger.new) {
 	                  lead.Ownerid =lead.Phone_Lead_Owner__c;

 Here's the Class:


public class TestchangeLeadOwner {
     // Methods for testing 
   @isTest static void test1() {
         profile StandardProfile = [select id from profile where name='Admin User'];
         User usrObj = [select id from User LIMIT 1];

         Lead ld = new Lead(Lastname='testLead', Company='companyTest' );

         ld.Phone_Lead_Owner__c = usrObj.id;

         insert ld;

         update ld;



 Here's that the test result is highlighting red


if (Trigger.new.size() == 1) {  10    for (Lead lead :trigger.new) {  11    lead.Ownerid =lead.Phone_Lead_Owner__c;



Any help and tips would be greatly appreciated.

Hi all, I'm  newbie in apex and visulaforce development, I have the following apex class:

public with sharing class UserAccountCtrl {
    public Id UserAccountId{get;set;}
    public String ErrorMessage{get;set;}
    public UserAccountCtrl(){  
            Id userId = UserInfo.getUserId();
            User us = [select Id, ContactId from User where Id =: userId];
            if(us.ContactId == null)
                ErrorMessage = 'The user logged is not related to any contact';
            Contact cont = [select Id, AccountId from Contact where Id =: us.ContactId];
            UserAccountId = cont.AccountId; 
        catch(Exception ex)
            ErrorMessage = ex.getMessage();


and visualforce code:

<apex:page controller="UserAccountCtrl" 
<a href="/{!UserAccountId}" target="_parent">Account</a>
How to write a test class for this?? Thanks in advance..


  • May 21, 2013
  • Like
  • 0

Hi Everyone, when I faced the too many queries error, then I realize how important this article is 



And I update all my code, use List for sObject, and put all queries out of loop. \

But it doesn't tell how to Where the update


Now I put update into the loop, because I have conditional statement.


Is there some method could check if List is changed or not? then update it? 

/>List<Country__c> mcs = Country__c.getall().values();
System.debug('Rakesh'+ mcs);
for(GFQuote__c a : qr1)
qrStatus = a.Quote_Request_Status__c;
List <Opportunity> ct = New List<Opportunity>( [select Name, id,CloseDate,StageName, Deal_Review_Date__c, Reason_Closed_Lost__c, Deal_Lost_Description__c, Lost_Comments__c, Next_Opportunity_To_Quote__c from Opportunity where id = :a.Deal__c Limit 1]);
for(Opportunity d : ct)
qr2 = [select Id,Launch_Date__c,name from GFQuote__c where Deal__c = : d.id];
qr3 = [select Id,name,Quote_Request_Status__c from GFQuote__c where Deal__c = : d.id AND Quote_Request_Status__c != 'QR Lost'];
if (a.Launch_Date__c== NULL)


Could anybody help. 

I have one field where I am populating the Value from User Table and saving inside one lookup field. 

In the controller when saving this value in Lookup Field its giving the error as :

"Error System.StringException: Invalid id:"




If I create 2 visualforce page VF1 and VF2 using the same Controller "MyController" would the "Total number of executed code statements" limit be contained in its own VF page? meaning, if VF1 calls VF2, then does the Script Execution Statements of VF1 count towards the "Total number of executed code statements" of VF2 as well? or are they counted seperately? 



I would like to increase the number of queries I have available.  The solution I have which goes over the limit I feel is elegent and works and is done! 


I feel like this limit on queries is limiting the developer to code to lower standards.

Hi i created a trigger which is working.but not working with bulkified(dataloader).please see my code,and let me know to bulkify this code

field in account object (Status_Contact) to be updated when a custom field (Project Status) on the custom Project Object gets updated.



trigger contactlookup on Project__c (after insert,after update) {

list<Project__c> proj=new list<Project__c>();
Map<Id,List<Project__c>> mapProject = New Map<Id,List<Project__c>>();
set<id>ids=new set<id>();
for(Project__c p1:trigger.new)

proj=[SELECT id,contact__r.Client_Status_Contact__c,contact__r.id from Project__c where Contact__c in:ids];

for(Project__c po :proj)

if(po.Contact__c != null)
List<Project__c> ProjectForKey =mapProject.get(po.Contact__c);
if(ProjectForKey == null)
ProjectForKey = new List<Project__c>();
mapProject.put(po.Contact__c, ProjectForKey);

list<contact> cont= new list<contact>();
cont=[select id ,name,Client_Status_Contact__c from contact];
contact c= new contact();
c.Client_Status_Contact__c =proj[0].contact__r.Client_Status_Contact__c;
for(Project__c p:trigger.new)
Update c;

Anyone know why setting Case.Status inside a loop using format() works, while attempting to set EmailMessage.Status inside a loop using format() fails?


System.DmlException: Insert failed. First exception on row 0; first error: INVALID_OPERATION, operation is not allowed: []


public class testingForLoopProblem {
    public testingForLoopProblem() {}

    @isTest static void Case_ForLoop_Success_Test() {
        Account acc01 = new Account(Name = 'success');
        insert acc01;

        Integer NUM_RECORDS = 6;
        List<Case> cases = new List<Case>();
        for (Integer counter = 0; counter < NUM_RECORDS; counter++){
            Case caseTemp = new Case();
            caseTemp.AccountId = acc01.Id;
            caseTemp.Subject = 'Test: : ' + counter;

            // Why does this work?
            caseTemp.Status = counter.format();

        insert cases;

    @isTest static void EmailMessage_ForLoop_Fail_Test() {
        Account acc01 = new Account(Name = 'fail');
        insert acc01;
        Case case01 = new Case(AccountId = acc01.Id);
        insert case01;
        Integer NUM_RECORDS = 6;
        List<EmailMessage> emails = new List<EmailMessage>();
        for (Integer counter = 0; counter < NUM_RECORDS; counter++){
            EmailMessage email = new EmailMessage();
            email.ParentId = case01.Id;

            // Why does this NOT work?
            email.Status = counter.format();

        insert emails;

 API Version 27.

  for(Task a : Trigger.old){
              if(a.OwnerId != UserInfo.getUserId()  && ProfileId  != '00e00000006qrDIAAY' )

                      a.addError('You are not authorised to delete this task!');


I have trigger to update Account depending on the order call data input.  The first and the third checking work and can update Account successfully.  However, the second one checking the "'1yr RP Quit" always shows the error "System.NullPointerException: Attempt to de-reference a null object" when it does "acclist.get(oc.Member__c).X1yr_Reserve_Program__c = FALSE".  Anyone can know why?



  Set<Id> accIds = new Set<Id>();

  for(Order_Call__c oc: Trigger.new){  

      if(oc.Call_Purpose__c == 'Order' || oc.Agreed_to_join_1yrRP__c == True ||  

         oc.Call_Purpose__c == '1yr RP Quit'){  


      }//end if    

  }//end for     

  Map<Id,Account> acclist = new Map<Id,Account>([select id, Last_Order_Date__c, X1yr_Reserve_Program__c, X1yrRP_Joined_Date__c,

              X1yrRP_Quit_Date__c, No_Of_Orders__c from Account where id in :accIds]);       

  for(Order_Call__c oc:Trigger.new){           

      if(oc.Call_Purpose__c == 'Order'){

         acclist.get(oc.Member__c).Last_Order_Date__c = oc.Order_Date__c;    

         string a = string.valueOf(acclist.get(oc.Member__c).No_of_Orders__c);      

         if(a == NULL){      

            acclist.get(oc.Member__c).No_of_Orders__c = 0;         

         }//end if 

         acclist.get(oc.Member__c).No_of_Orders__c = acclist.get(oc.Member__c).No_of_Orders__c + 1;      

      //end if        

      if(oc.Call_About__c == '1yr RP Quit'){        

         acclist.get(oc.Member__c).X1yr_Reserve_Program__c = FALSE;

         acclist.get(oc.Member__c).X1yrRP_Quit_Date__c = date.today();       

      }//end if         

      if(oc.Agreed_to_join_1yrRP__c == True){          

         acclist.get(oc.Member__c).X1yr_Reserve_Program__c = TRUE;

         acclist.get(oc.Member__c).X1yrRP_Joined_Date__c = date.today();

      }//end if            

  }//end for          





my <apex:datatable> has multiple columns containing input field ... selectList...

is it possible to sort my table when header is clicked ??

and if yes... which is best way..using controller function or jquery plugin ??

i have tried tableSorter plugin but its not working properly.....

  • March 12, 2013
  • Like
  • 0



Could you please help me write a test class for my trigger? I managed to get 10% covered, but since I am not a programmer I am having a hard time understanding how to correct it to get more. Thank you in advance!


This is my Trigger:

trigger CreateAssetonClosedWon on Opportunity (after insert, after update) {
     for(Opportunity o: trigger.new){ 
      if(o.isWon == true && o.HasOpportunityLineItem == true && o.RecordTypeId == '012200000004fxZ'){
         String opptyId = o.Id;
         OpportunityLineItem[] OLI = [Select UnitPrice, Quantity, PricebookEntry.Product2Id, PricebookEntry.Product2.Name, Description, Converted_to_Asset__c  
                                      From OpportunityLineItem 
                                      where OpportunityId = :opptyId and Converted_to_Asset__c = false];
         Asset[] ast = new Asset[]{};
         Asset a = new Asset();
         for(OpportunityLineItem ol: OLI){
            a = new Asset();
        a.AccountId = o.AccountId;
            a.Product2Id = ol.PricebookEntry.Product2Id;
            a.Quantity = ol.Quantity;
            a.Price =  ol.UnitPrice;
            a.PurchaseDate = o.CloseDate;
            a.Status = 'Purchased';
            a.Description = ol.Description;
            a.Name = ol.PricebookEntry.Product2.Name;
            ol.Converted_to_Asset__c = true;
      update OLI; 
      insert ast;


How to check field value starts with 'World***'


 if(T1.WhatId  ==  o.id && T1.Subject == 'Email: 'World.........'' ){

  • March 11, 2013
  • Like
  • 0