• Saran
  • NEWBIE
  • 393 Points
  • Member since 2013
  • Jr Software Engg
  • MST Solutions

  • Chatter
    Feed
  • 12
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 7
    Questions
  • 99
    Replies

I have this apex trigger but getting the following error when trying to delete contract product from an opportunity.  Could someone please let me know what I need to fix so I can delete contract products?

trigger Contract_Product_Delete_Update_Accounts_and_Contracts on Contract_Product__c (after delete) 
{  
  system.debug('DELETE TRIGGER FIRSTRUN VARIABLE: ' + Account_Contract_Update_Class.FirstRun);
  if(Account_Contract_Update_Class.FirstRun == true)
  {
    Account_Contract_Update_Class.FirstRun = false;
    system.debug('CONTRACT PRODUCT DELETE TRIGGER!!!!');
    String ObjectDMLType ='ContractProductDelete';
    set<ID> TheseAccountIDs = new set<id>(); //Set of Account IDs that have Contract Products. 
                        //These Accounts Need to be updated by checking All their active Contract Products
    set<id> TheseContractIDs = new set<id>();                      
    list<string> Products = new list<string>();
    for(Contract_Product__c cp : trigger.old)
    {
      TheseAccountIds.add(cp.Account__c);  
      TheseContractIds.add(cp.Contract__c);  
      Products.add(string.valueof(cp.Product_Family__c));
    }    
    system.debug('Number of Products removed: ' + trigger.old.size());  
    system.debug('These are the accounts that will be updated: ' + TheseAccountIds);
    system.debug('These are Products being deleted: ' + Products);    
    
    //Update the Contract
    Account_Contract_Update_Class.UpdateContracts(TheseContractIDs, ObjectDMLType);  
    //Update the Account
    Account_Contract_Update_Class.UpdateAccounts(TheseAccountIDs, ObjectDMLType);
  }
//last brackett
}


 

ERROR I am getting:
Validation Errors While Saving Record(s)
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger Contract_Product_Delete_Update_Accounts_and_Contracts caused an unexpected exception, contact your administrator: Contract_Product_Delete_Update_Accounts_and_Contracts: execution of AfterDelete caused by: System.QueryException: No such column 'BillingAddress' on entity 'Contract'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names.: Class.Account_Contract_Update_Class.UpdateContracts: line 238, column 1". 

Click here to return to the previous page.
 

Hi, I need test class for below controller.

public class Sum
{
 public integer first { get; set;}
  public integer second { get; set;}
  public integer result {get; set;}
  public void add()
  {
   result = first + second ;
  }
 public void sub()
  {
   result = first - second ;
   }
 public void mul()
  {
   result = first * second ;
   }
public void mod()
 {
   result = first / second ;
 }
  }
Hai,
I have writter a trigger on custom obj called as Horticulture__c to avoid duplicate entries/names in the table. While executing my trigger it shows error like "Initial term of field expression must be a concrete SObject: List<Horticulture__c>". pls give solution.
trigger Duplicate_Farmer_Horti on Horticulture__c (before insert,before update)
{
    for (Horticulture__c H:Trigger.New)
    {
        List<Horticulture__c> Horti = [select id from Horticulture__c where Applicant_Name__c=:H.Applicant_Name__c];
        if(Horti.size()>0)
        {
            Horti.Applicant_Name__c.addError('You can not create duplicate name');
        }            
        
    }

}
I am running into this issue, I have fixed it before by adding a boolean but even with it on this example I still get the same error. It's throwing the error on line 52. 
 
public class Account_HDL {

private static boolean updatecstimp = false;
private static boolean dontupdatecstimp = false;
private static boolean newreview = false;
    
    
public static void UpdateCSTImp(Account[] acc){
list<CST_Implementation__c> cstimplist = new List<CST_Implementation__c>();
Set<String> cstimpIds = new Set<String>();
list<Account> updateacclist = new List<Account>();
Set<String> updateaccIds = new Set<String>();


    
    for(Account accs : acc){
        //updateaccIds.add(accs.Id);
        updateacclist  = [select Id, CST_Fully_Implemented_On__c, CST_Implementation_Stage__c, Days_from_RC_to_Imp__c, Last_Review_Date__c, 
                 Number_of_CST_Implemented_Services__c, Number_of_CST_Imp_Services_Complete__c, Number_of_CST_Imp_Services_Not_Complete__c, 
                 Latest_CST_Implementation__c, Regarding_Annual_Review__c, Review_FP_Result__c, Review_ROA_Result__c, Review_Super_Result__c 
                 from Account where Id =: trigger.new];
        
            Account oldAcc = (Account)Trigger.oldMap.get(accs.Id);
        
        for(Account updateacc : updateacclist){
           if(oldAcc.Regarding_Annual_Review__c != accs.Regarding_Annual_Review__c && accs.Regarding_Annual_Review__c != null
              && dontupdatecstimp == false && newreview == false){
               dontupdatecstimp = true;
               updateacc.CST_Fully_Implemented_On__c  = null;
               updateacc.CST_Implementation_Stage__c  = ''; 
               updateacc.Last_Review_Date__c  = null; 
               updateacc.Number_of_CST_Implemented_Services__c  = null; 
               updateacc.Number_of_CST_Imp_Services_Complete__c  = null; 
               updateacc.Number_of_CST_Imp_Services_Not_Complete__c  = null; 
               updateacc.Review_FP_Result__c  = ''; 
               updateacc.Review_ROA_Result__c  = ''; 
               updateacc.Review_Super_Result__c  = ''; 
               //create new cst imp for annual review   
                            List<CST_Implementation__c> addcstimplist = new list<CST_Implementation__c>();
                           for(CST_Implementation__c newcstimp : addcstimplist){
                            
                            addcstimplist.add(new CST_Implementation__c(
                            Name = 'Annual Review',
                            Related_Account__c = updateacc.Id
                            ));
                           }
                           insert addcstimplist;
                        
            }
           }
             if(updateacclist.size()>0 && dontupdatecstimp == true && newreview == false){
                update updateacclist;
                newreview = true;
               } 
        cstimpIds.add(accs.Latest_CST_Implementation__c);
        cstimplist = [select Id  from CST_Implementation__c where ID in : cstimpIds];
        for(CST_Implementation__c relatedcstimp : cstimplist){
            if(dontupdatecstimp == false){
            if( oldAcc.CST_Fully_Implemented_On__c != accs.CST_Fully_Implemented_On__c){
                relatedcstimp.CST_Fully_Implemented_On__c = accs.CST_Fully_Implemented_On__c;
                updatecstimp = true;
            }
            if( oldAcc.CST_Implementation_Stage__c != accs.CST_Implementation_Stage__c){
                relatedcstimp.CST_Implementation_Stage__c = accs.CST_Implementation_Stage__c;
                updatecstimp = true;
            }
            if( oldAcc.Last_Review_Date__c != accs.Last_Review_Date__c){
                relatedcstimp.Last_Review_Date__c = accs.Last_Review_Date__c;
                updatecstimp = true;
            }
            if( oldAcc.Number_of_CST_Implemented_Services__c != accs.Number_of_CST_Implemented_Services__c){
                relatedcstimp.Number_of_CST_Implemented_Services__c = accs.Number_of_CST_Implemented_Services__c;
                updatecstimp = true;
            }
            if( oldAcc.Number_of_CST_Imp_Services_Complete__c != accs.Number_of_CST_Imp_Services_Complete__c){
                relatedcstimp.Number_of_CST_Imp_Services_Complete__c = accs.Number_of_CST_Imp_Services_Complete__c;
                updatecstimp = true;
            }
            if( oldAcc.Number_of_CST_Imp_Services_Not_Complete__c != accs.Number_of_CST_Imp_Services_Not_Complete__c){
                relatedcstimp.Number_of_CST_Imp_Services_Not_Complete__c = accs.Number_of_CST_Imp_Services_Not_Complete__c;
                updatecstimp = true;
            }
            if( oldAcc.Review_FP_Result__c != accs.Review_FP_Result__c){
                relatedcstimp.Review_FP_Result__c = accs.Review_FP_Result__c;
                updatecstimp = true;
            }
            if( oldAcc.Review_ROA_Result__c != accs.Review_ROA_Result__c){
                relatedcstimp.Review_ROA_Result__c = accs.Review_ROA_Result__c;
                updatecstimp = true;
            }
            if( oldAcc.Review_Super_Result__c != accs.Review_Super_Result__c){
                relatedcstimp.Review_Super_Result__c = accs.Review_Super_Result__c;
                updatecstimp = true;
            }
            }
        } 
        if(cstimplist.size()>0 && updatecstimp == true && dontupdatecstimp == false){
        update cstimplist;
        }
    }
       
}
}

 
Hi,

I am trying to update the Old Account's Opportunity description field as Opportunity Owner's email address, for all the contacts whose Account Id is updated. Here is the code I tried. When I tried hard coding description as account Id it worked. But how to get opportunity owner's email address?

trigger accountchange on Contact (after insert, after update) {
  //This queries all Accounts related to the incoming Contact records in a single SOQL query.                                      
  // List<Contact> contactwithAccounts = [select id, firstname, AccountId from Contact where Id IN :Trigger.newMap.keySet()];

  Map<Id, Opportunity> OppToUpdate = new Map<Id,Opportunity>();
  Map<Id,Contact> Mp = new Map<Id,Contact>(); // Store Account Id and contact object
    //indexed for loop
    for(integer i=0; i<trigger.new.size(); i++){
        if(trigger.new[i].AccountId != trigger.old[i].AccountId){  
            System.debug('trigger.old[i].AccountId : '+trigger.old[i].AccountId + ':' + trigger.old[i].Account);
            Mp.put(trigger.old[i].AccountId,trigger.new[i]);   // store account Id and contact object                          
      }                   
    }
    // Update Opportunity of old account with description as opty owner email id
    List<Id> OId = new List<Id>();
    for(Opportunity opp: [Select Id, Description, OwnerId from Opportunity where AccountId =:Mp.Keyset()]){
            opp.Description = '----Added through Trigger - Opty Owner Id' + opp.OwnerId + '--Contact Owner Id';
            OId.add(opp.OwnerId);     // get Opportunity owner id in OId List.       
            OppToUpdate.put(opp.Id, opp);        
    }
    
    Map<Id,User> us1 = new Map<Id,User>([SELECT Id,Email FROM User where id =: OId]); 
    // Throws compilation error as line 27:16 no viable alternative at character'' for above line.
    for (Id userId : us1.Keyset()){
        for(Opportunity op : OppToUpdate){
            if(userId == OppToUpdate.get(op).OwnerId){
                op.Description = us1.get(userId).Email;
            }
        }
    }    
    
    //Now outside the FOR Loop, perform a single Update DML statement. 
   update OppToUpdate.values();
}
Hi,

Here is my scenario:

I have a CUSTOM Object, when any attachment is uploaded for this CUSTOM OBJECT record, I am populating 2 fields with the values of attachment record onto the CUSTOM OBJECT via a trigger.

If the attachment is deleted there are below cases that needs to be implemented:
Case-1: If all the ATTACHMENT records are deleted for this CUSTOM OBJECT ---> CLEAR those fields
Case-2: If any other ATTACHMENT exists after deleteing a single attachment​ -- > Update these fields with the MOST RECENT ATTACHMENT values.

Here is the code which I have tried;


Below is the code I have tried - Can you help me understand whether this is going to hit any SOQL LIMIT ?

public void callAfterDeleteMethods(List<Attachment> AList)
    {         
        //Local variables        
        set<Id> policyIDs = new set<Id>();
        List<Attachment> attachList = new List<Attachment>();
        Map<CUSTOM_OBJECT__c,List<Attachment>> Policy_TO_AttachmentList_Map = new Map<CUSTOM_OBJECT__c,List<Attachment>>();  //Map PUG-Object To Respective Attachment List
        List<CUSTOM_OBJECT__c> pugList;
        
        for(Attachment att : AList)          //Taking All Policy IDs in Context
        {
            String objectAPIName = (String) att.ParentId.getSObjectType().getDescribe().getName();
            System.debug('FROM Delete Method - objectAPIName = '+objectAPIName);
            if(objectAPIName.equalsIgnoreCase('CUSTOM_OBJECT__c'))
                    policyIDs.add(att.ParentId);
        }

        
        if(policyIDs.size()>0)    //if list of incoming list records to be deleted are not ZERO
        {        
              pugList = [SELECT Id,Upload_Date__c,User__c  FROM CUSTOM_OBJECT__c WHERE Id in: policyIDs];  //List to Hold PUG Objects
        }      
        
         if(pugList.size()>0)      
                {                 

                    for(CUSTOM_OBJECT__c pug : pugList)  //For each PUG Object get Attachments listed and Mapped
                      {
                            for(Attachment Att : [SELECT Id,CreatedDate,CreatedById FROM Attachment WHERE ParentId =: pug.Id ORDER BY createdDate DESC])
                                {
                                    attachList.add(Att);  //Make the list
                                }
                    
                            Policy_TO_AttachmentList_Map.put(pug,attachList); //Policy-Object --> Corresponding Attachment List
                    
                      }
                      
                      for(CUSTOM_OBJECT__c pug : pugList)
                      {
                          if(Policy_TO_AttachmentList_Map.containsKey(pug))
                          {
                              if(Policy_TO_AttachmentList_Map.get(pug).size()>0)  //if attachments exists for policy
                              {
                                    Attachment temp = Policy_TO_AttachmentList_Map.get(pug).get(0);          
                                    pug.Upload_Date__c = (Datetime)temp.CreatedDate;
                                    pug.User__c = temp.CreatedById;

                                    policyUpdatelist.add(pug);
                              }
                              else
                              {     
                                    pug.Upload_Date__c = null;
                                    pug.User__c = null;
               
                                    policyUpdatelist.add(pug);
                              }
                              
                          }
                      }
                     

                }

          update policyUpdatelist;

          firstRun = false;        //To Avoid Recursive Calls in the Context

        
    }//End-Of-Delete Method



/*******************************************************************************/

In the above code I had to write NESTED For Loops to fetch the Attachment list for every CUSTOM OBJECT RECORD.


for(CUSTOM_OBJECT__c pug : pugList)  //For each PUG Object get Attachments listed and Mapped
                      {
                            for(Attachment Att : [SELECT Id,CreatedDate,CreatedById FROM Attachment WHERE ParentId =: pug.Id ORDER BY createdDate DESC])
                                {
                                    attachList.add(Att);  //Make the list
                                }
                    
                            Policy_TO_AttachmentList_Map.put(pug,attachList); //Policy-Object --> Corresponding Attachment List
                    
                      }


I think this may cause to hit SOQL LIMIT, Can any one suggest any other way to  this ?
Senario - I have created a button on Contact which when clicked it redirects to Lead page with prepulated fields like company name, address and so on. It has two custom fields one lookup which alows to choose a user who this new lead would be refered to and othe a field which stores the refered by user name. I got this part now the tricky part is i need to write a trigger as when its clicked on saved button the new lead owner should be saved on the refered to user not on the current user. By default lead owner is stored on current user name. Hence i decided to write a trigger before insert and one after insert which sends a email alert to the new lead owner to which this is refered to or created for. Code looks like missing quite a few things here. Any help would be highly appreciated.
public class LeadTriggerHelperClass {
public static void isBeforeInsert(List<Lead> LeaList)
{Lead Lea = New Lead();
 
    If(Lea.RecordTypeid == '01228000000YtCD')
    {
      Lea.OwnerId = Lea.Reffered_To__c;
    	Insert Lea;
    }
}

public static void isAfterInsert(Lead LeaList)
{
    Lead EmailLead = [SELECT id FROM Lead WHERE id = :LeaList.Id];
  String emailMessage ='A New Lead '
             +'Has been Referred '
             +'By a Sales Representative.' 
             +' For Account'+ EmailLead.Company 
             +' Requirement of ' 
             + EmailLead.Description +
             ' Lead Number'
             + EmailLead.ID 
             +' records were not updated successfully.';
        
        Messaging.SingleEmailMessage mail = 
              new Messaging.SingleEmailMessage();
        String[] toAddresses =new String[] {EmailLead.createdBy.email};
        mail.setToAddresses(toAddresses);
        mail.setReplyTo('noreply@salesforce.com');
        mail.setSenderDisplayName('Lead Created');
        mail.setSubject('Lead Created');
        mail.setPlainTextBody(emailMessage);
        mail.setHtmlBody(emailMessage);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] 
                           { mail });
  
}
 }

 
I have a requirement to check for the attachments on a Object;
If there are no attachments I have to clear some fields up on delete.
if only a single atatchment deleted and still some attachments left on the custom object - get the recent attachment values and update on the object (Parent = Account)

Please check the trigger code below:

trigger TestAttachments on Attachment (after insert,after delete) {

    
    
    //Variables
    Map<Id,Attachment> Account_TO_Attachment = new Map<Id,Attachment>();
    Map<Id,Integer> Account_TO_AttachmentCount = new Map<Id,Integer>();
    List<Account> updateAccounts = new List<Account>();
    List<ID> ListparentIDs = new List<ID>();
    
    if(trigger.isinsert)
    {
    
    
        //Take all Account Attachments only
        for(Attachment A : Trigger.new)
        {
            //Check the Parent Object and take only relevant
            String objectAPIName = (String) A.ParentId.getSObjectType().getDescribe().getName();
            System.debug('objectAPIName = '+ objectAPIName);
            if(objectAPIName.equalsIgnoreCase('Account')){
                    
                    Account_TO_Attachment.put(A.ParentId,A);
                    
            }        
                    
                    
        }
        
             
       
        
        for(Account Acc : [SELECT Id,Upload_Date__c,Upload_User__c,Upload_Link__c FROM Account where Id in :Account_TO_Attachment.keyset()])
        {
            if(Account_TO_Attachment.containskey(Acc.id)){
                Attachment temp = Account_TO_Attachment.get(Acc.Id);
                Acc.Upload_Date__c = (DateTime)temp.CreatedDate;
                Acc.Upload_User__c = temp.CreatedById;
                               
                updateAccounts.add(Acc);
            }
        }
        
        if(updateAccounts.size() > 0)
           update updateAccounts;
           
         } //End-Of-isInsert 
    
    //Delete Event
    
    if(trigger.isdelete)
        { 
            for(Attachment A : Trigger.old)
                {
                    ListparentIDs.add(A.ParentId);
                }

                    //List<Proposal__c> co = [select id, Attachment_Added__c from Proposal__c where id =: Trigger.old[0].ParentId];
                    List<Account> co = [select id,Upload_Date__c,Upload_User__c  from Account where id in: ListparentIDs];
         

            if(co.size()>0)         

                {                 

                List<Attachment> allChildren = [Select id from Attachment where parentid = :co[0].id];

                if(allChildren != null && allChildren.size() == 0)           

                    //co[0].Attachment_Added__c = false;             

                    update co;         

                }

        } //End Of Delete
    
    
    
    
    
    
    
    
    
    
    
}
 
I have a requirement where I need to create a button on lead page when clicked it should redirect to Contact page with prepopulated values like  Lead Company Name - Account Name, Lead Phone - Contact Phone and so on.(standard pages) dont want to create a VF Page. Any suggestions would be appreciated.
Hi,
While I am executing the class ‘LeadtoMember’, I am facing the the following issue.

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger LeadConversion caused an unexpected exception, contact your administrator: LeadConversion: execution of BeforeUpdate caused by: System.DmlException: Delete failed. First exception on row 0 with id 00Q9000000pNJH4EAO; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = 00Q9000000pNJH4) is currently in trigger LeadConversion, therefore it cannot recursively delete itself: []: Class.LeadtoMemberConversn.conversion: line 18, column 1

============================

The class is as follows.
public class LeadtoMemberConversn {
List<Lead> leads;
List<Member__c> members;

public LeadtoMemberConversn(List<Lead> leadList){
leads=leadList;
members= new List <Member__c>();
}
public void conversion(){
for(Lead l: leads){
Member__c member = new member__c();
member.Name = l.FirstName +” +l.LastName;
member.Email__c = l.Email;
members.add(member);
}
insert members;
List<Lead> todel= leads.deepClone(true);
delete todel;
}

public List<Member__c> getMembers(){
return members;
}
}

And the trigger is
trigger LeadConversion on Lead (before update){
List<Lead> leads= new List<Lead>();
for(Lead l:Trigger.new){
if(l.Status== ‘Member’){
leads.add(l);
}
LeadtoMemberConversn lmc= new LeadtoMemberConversn(leads);
lmc.conversion();
System.debug(‘values’+ lmc.getMembers());
}
}

While saving the Lead record’s status to Members, I am getting the error.


Thanks in Advance.
Reshmi.
Hi,

I dont know why my page shows this error. Please give a solution. My VF page is like as below


<apex:page standardController="Interrogate__c" extensions="ApsTestController">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection >
                1. A compiler converts the Java program into an intermediate language representation called ____________.<br></br>
                         <apex:selectradio >
                          <apex:selectOptions value="{!X1optionsbelow}"/><br></br><br></br>
                           </apex:selectradio>
                        
                       2. _____________ operator is used to create an object.<br></br>
                            <apex:selectradio >
                           <apex:selectOptions value="{!x2optionsbelow}"/>
                           </apex:selectradio>
                       
            </apex:pageBlockSection>
                <apex:pageBlockButtons location="bottom">
                 <apex:commandButton value="Finish" action="{!save1}" />
                </apex:pageBlockButtons>
        </apex:pageBlock>    
    </apex:form>
</apex:page>

My controller class is as below:

public class ApsTestController{
public Interrogate__c Interrogate{get;set;}
public string x1{get;set;}
public string x2{get;set;}
public string id{get;set;}
public List<SelectOption> x1optionsbelow{get;set;}
public List<SelectOption> x2optionsbelow{get;set;}
public ApsTestcontroller(apexpages.standardcontroller controller)

{


Interrogate = new Interrogate__c();
interrogate = (interrogate__c)controller.getrecord();
x1optionsbelow=new List<SelectOption>();
Schema.DescribeFieldResult statusFieldDescription1=Interrogate__c.X1__c.getDescribe();
        for (Schema.Picklistentry picklistEntry:statusFieldDescription1.getPicklistValues()){
        x1optionsbelow.add(new SelectOption(pickListEntry.getValue(),pickListEntry.getLabel()));
            if (picklistEntry.defaultValue){
            Interrogate.X1__c= pickListEntry.getValue();
            }  
         } 
x2optionsbelow=new List<SelectOption>();
Schema.DescribeFieldResult statusFieldDescription=Interrogate__c.X2__c.getDescribe();
        for (Schema.Picklistentry picklistEntry:statusFieldDescription.getPicklistValues()){
        x2optionsbelow.add(new SelectOption(pickListEntry.getValue(),pickListEntry.getLabel()));
            if (picklistEntry.defaultValue){
            Interrogate.X2__c= pickListEntry.getValue();
            }  
         } 

}
public pagereference save1()

    {
        interrogate__c inte=new interrogate__c();
        inte = [select id, name, name__c, X1__c, X2__c from interrogate__c where id=:Interrogate.id];
        inte.X1__c = Interrogate.X1__c;
        inte.x2__c = Interrogate.x2__c;
        upsert inte;
        pagereference ref;
        ref = new pagereference('/apex/ApsTest?id='+interrogate.id);
        ref.setredirect(true);
        return ref;
    }
}

I want to update the X1 and X2 feilds in interrogate object. But it is not updating.
Hi Team,

I want to populate account id  value into the field (BISM_Officer__c) of object Clarity_Effort__c. 

Below is the requirement in brief 
I have two objects Clarity and Account.  If any record is created with out BISM_Officer__c then, there is field Resource_Name__c in Clarity object and in Account there is field Clarity_Effort_Resource_Name__c if these two are matching, the accountId of value with Clarity_Effort_Resource_Name__c need to popualte in Clarity record. The below code is working  for single record, but not bulk records.

Would you please guide me with above requirement.


trigger  AccountPopulate on Clarity_Effort__c (before insert, before update) 
{

     String AccountId;

     Map<String,List<Clarity_Effort__c>> AccountClarityList = new Map <String,List<Clarity_Effort__c>>();
     
     
     List<Account>  AccountList = new List<Account> ();
     
    // List<Clarity_Effort__c> UpdateClarityList = new List<Clarity_Effort__c>();
     List<Clarity_Effort__c> NewClartiryList= new List<Clarity_Effort__c>();
     
     List<string> ClarityWithoutAccounts = new List<string>();
   
     for (Clarity_Effort__c  CE : Trigger.new) 
      
       {
     
          if (Trigger.isInsert || Trigger.isUpdate)
          {
           if(CE.BISM_Officer__c == null)
       
             {
                 ClarityWithoutAccounts.add(CE.Resource_Name__c);
                 NewClartiryList.add(CE);
                 
             } 
          }      
             
            system.debug( 'Naresh'+ ClarityWithoutAccounts);
            
                                     
       }       
       
        AccountList = [SELECT Id FROM Account WHERE Clarity_Effort_Resource_Name__c IN : ClarityWithoutAccounts];  
        

          for(Account Acc : AccountList) 
          
          
           {
              if(!AccountClarityList.containsKey(Acc.Id))
              
                  {
                
                     AccountClarityList.put(Acc.id, new List<Clarity_Effort__c>());
                     AccountClarityList.get(Acc.Id); 
                     AccountId= Acc.Id;  
                     
                  }
              
              system.debug('AccountListCL'+AccountClarityList);
              
            for (Clarity_Effort__c  CEU : NewClartiryList ) 
        
               {
          
                   CEU.BISM_Officer__c = AccountId;
                   // UpdateClarityList.add(CEU);
               }          
              

                 
           }                         
        
          
       
      
 }

Thanks,
Kumar
Hi All,

I have a trigger in lead object. Below is trigger functionality,
In after insert of lead trigger I am calling the future method.
In the future method I am updaing the same lead records.
Now, In the lead Update I am converting the lead.

Have done this because I wanted lead conversion to take place in seperate transaction.

Now, When I insert leads its getting converted to contact and opportunity which is fine.

But the problem is when I try to load leads under the campaign, below is the screen shot where I am trying to load.

User-added image


So When I load lead through the campaign member, It should convert to contact and the contact must be added as the campaign member.

But for me the lead is getting converted as soon as I am loading the records. But when I refresh the campaign none of the contacts are associated.

Also during the web to lead form submission. Since its single records I guess its creating contact and that contact is added as campaign member.

Let me know your suggestions,

Thanks,
Saraz
  • May 10, 2016
  • Like
  • 0
Hi All,

I have a question in sending a callout.

My Endpoint is : 'http://www.XXXXXXX.YYYYYY.NNN/ZZZZ/MMMM/'

Uer id and pssword as set a header.

So my request will be like,

HttpRequest req = new HttpRequest();
req.setEndpoint('http://www.XXXXXXX.YYYYYY.NNN/ZZZZ/MMMM/');
req.setMethod('GET');
req.setHeader('username', 'AAAAAAAAA');
req.setHeader('password', 'QQQQQQQQQ');

Http http = new Http();
HttpResponse res = http.send(req);
system.debug('$$$$$' + res.getBody());

When i try this i am getting error someting invalid.

But the strange thing is when i directly appending it to url its working good.

HttpRequest req = new HttpRequest();
req.setEndpoint('http://www.XXXXXXX.YYYYYY.NNN/ZZZZ/MMMM/?username=AAAAAAAAA&password=QQQQQQQQQ');
req.setMethod('GET');

Http http = new Http();
HttpResponse res = http.send(req);
system.debug('$$$$$' + res.getBody());

Now in the debug i getting the correct response.

Can anyone tell me why i cant use setHeader Method.


Thanks,
  • September 03, 2015
  • Like
  • 0
Hi All,

I have a question in sending a callout.

My Endpoint is : 'http://www.XXXXXXX.YYYYYY.NNN/ZZZZ/MMMM/'

Uer id and pssword as set a header.

So my request will be like,
 
HttpRequest req = new HttpRequest();
req.setEndpoint('http://www.XXXXXXX.YYYYYY.NNN/ZZZZ/MMMM/');
req.setMethod('GET');
req.setHeader('username', 'AAAAAAAAA');
req.setHeader('password', 'QQQQQQQQQ');

Http http = new Http();
HttpResponse res = http.send(req);
system.debug('$$$$$' + res.getBody());

When i try this i am getting error someting invalid.

But the strange thing is when i directly appending it to url its working good.
 
HttpRequest req = new HttpRequest();
req.setEndpoint('http://www.XXXXXXX.YYYYYY.NNN/ZZZZ/MMMM/?username=AAAAAAAAA&password=QQQQQQQQQ');
req.setMethod('GET');

Http http = new Http();
HttpResponse res = http.send(req);
system.debug('$$$$$' + res.getBody());

Now in the debug i getting the correct response.

Can anyone tell me why i cant use setHeader Method.

Thanks,
  • September 03, 2015
  • Like
  • 0
Hi All,

When we create a Quote (i.e) child of Contact. The standard Email and Phone field in the quote will be auto-populated based on the selected contact.

Now the requirement is that, We have to auto-populate the Standard Billing and Mailing address fields of quote based on the selected contact Billing and Mailing address fields.

Note: we want to pre populate. Not to populate after it is inserted or updated. 

Thanks ,
Saraz
  • June 03, 2015
  • Like
  • 0
Hi All,

I have a problem in converting the body of pdf file to a string. 

I tried something like this
Say for example the pdf file is stored in static resource :

My code looks like:
blob b = [select body from staticResource where name = 'testDoc'].body;
string s = b.tostring(); // here i am getting an error like "blob is not a valid UTF-8" 

I found what is the casue but I am not able to overcome that.
The issue is that the body of pdf will have some special character like " ê , ç , ã ".

So that it is showing such error I think. Can anyone help me out !!

Thanks in advance.
  • February 01, 2015
  • Like
  • 0
Hi All,

I tried to send a  mock callout after inserting the collabrotion group in apex test calass. I am getting an error "You have uncommited work pending".

Code snippet:-

CollaborationGroup myGroup = new  CollaborationGroup();
            myGroup.name = 'Test';
            myGroup.OwnerId =userId;
            myGroup.CollaborationType= 'Public';
            insert myGroup;

          Test.startTest();          
               Test.setMock(HttpCalloutMock.class, mock);
               // calling callout methods.               
           Test.stopTest()

Though both are differnt transaction it shows the above error message.

Thanks in Advance.
saraz
 
  • January 14, 2015
  • Like
  • 0
Hi All,

Is there is any standard method to convert the following string value to salesforce date format

december 14, 2014 To salesforce date format
  • December 30, 2015
  • Like
  • 0
How to write a trigger to sum like
Fee Paid Details = First Installment + Second Installment or Paid Full Fee
 ​where Fee Paid  Details is class object's field and remaning three like First Installment ,Second Installment , Paid Full Fee is Contact object's field..??


 

I have this apex trigger but getting the following error when trying to delete contract product from an opportunity.  Could someone please let me know what I need to fix so I can delete contract products?

trigger Contract_Product_Delete_Update_Accounts_and_Contracts on Contract_Product__c (after delete) 
{  
  system.debug('DELETE TRIGGER FIRSTRUN VARIABLE: ' + Account_Contract_Update_Class.FirstRun);
  if(Account_Contract_Update_Class.FirstRun == true)
  {
    Account_Contract_Update_Class.FirstRun = false;
    system.debug('CONTRACT PRODUCT DELETE TRIGGER!!!!');
    String ObjectDMLType ='ContractProductDelete';
    set<ID> TheseAccountIDs = new set<id>(); //Set of Account IDs that have Contract Products. 
                        //These Accounts Need to be updated by checking All their active Contract Products
    set<id> TheseContractIDs = new set<id>();                      
    list<string> Products = new list<string>();
    for(Contract_Product__c cp : trigger.old)
    {
      TheseAccountIds.add(cp.Account__c);  
      TheseContractIds.add(cp.Contract__c);  
      Products.add(string.valueof(cp.Product_Family__c));
    }    
    system.debug('Number of Products removed: ' + trigger.old.size());  
    system.debug('These are the accounts that will be updated: ' + TheseAccountIds);
    system.debug('These are Products being deleted: ' + Products);    
    
    //Update the Contract
    Account_Contract_Update_Class.UpdateContracts(TheseContractIDs, ObjectDMLType);  
    //Update the Account
    Account_Contract_Update_Class.UpdateAccounts(TheseAccountIDs, ObjectDMLType);
  }
//last brackett
}


 

ERROR I am getting:
Validation Errors While Saving Record(s)
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger Contract_Product_Delete_Update_Accounts_and_Contracts caused an unexpected exception, contact your administrator: Contract_Product_Delete_Update_Accounts_and_Contracts: execution of AfterDelete caused by: System.QueryException: No such column 'BillingAddress' on entity 'Contract'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names.: Class.Account_Contract_Update_Class.UpdateContracts: line 238, column 1". 

Click here to return to the previous page.
 

I am working on an apex page. I want the value of Quantity product to be NULL 
<apex:inputText value="{!QuantityProduct}" label="Quantity"/>
when command button action is executed as shown below:
<apex:commandButton action="{!ProcessSelected}" value="Add Selected Items" reRender="block2,errors" oncomplete="clearName();"/>
Below is VF page 
<apex:page standardController="Quote" extensions="ContactSearchController7" sidebar="false">
  <apex:form >
  <apex:pageMessages id="errors" />
  <apex:commandButton action="{!BackToQuote}" value="Back to Quote"/>
  <apex:pageBlock title="Find Me An Item!" mode="edit">
   	<apex:commandButton action="{!ProcessSelected}" value="Add Selected Items" reRender="block2,errors" oncomplete="clearName();"/>
  	<table width="100%" border="0">
  	<tr>  
    	<td width="200" valign="top">
      	<apex:pageBlock title="Parameters" mode="edit" id="criteria">
      	<script type="text/javascript">
      	function doSearch() {
        	searchServer(
          	document.getElementById("Name").value,
          	document.getElementById("Description").value,
          	document.getElementById("ProductType").value
          	);
      	}
     	function clearName() {
     			document.getElementById("Name").value = '';
            	document.getElementById("Description").value = '';
            	document.getElementById("ProductType").value = '';
			}
      </script> 
      <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors" >
          <apex:param name="Name" value="" />
          <apex:param name="Description" value="" />
          <apex:param name="ProductType" value="" />
      </apex:actionFunction>
      <table cellpadding="2" cellspacing="2">
       <tr>
        <td style="font-weight:bold;">Item #<br/>
        <input type="text" id="Name" onkeyup="doSearch();"/>
        </td>
      </tr> 
       <tr>
        <td style="font-weight:bold;">Description<br/>
        <input type="text" id="Description" onkeyup="doSearch();"/>
        </td>
      </tr> 
       <tr>
        <td style="font-weight:bold;">Product Type<br/>
        <input type="text" id="ProductType" onkeyup="doSearch();"/>
        </td>
      </tr>  
     </table>
   </apex:pageBlock>
        
   <apex:pageBlock title="Quantity" mode="edit" id="criteria2">
       <table cellpadding="2" cellspacing="2">
       <tr>
        <td style="font-weight:bold;">Quantity<br/>
         <apex:inputText value="{!QuantityProduct}" label="Quantity"/>
        </td>
      </tr> 
      </table>
   </apex:pageBlock>
    </td>
    <td valign="top">
  <apex:pageBlock mode="edit" id="results">
        <apex:pageBlockTable value="{!lstSetController}"  var="obj">
           <apex:column >
             <apex:facet name="header">
               <apex:inputCheckbox />
             </apex:facet>
            <apex:inputCheckbox value="{!obj.isSelected}" id="InputId"/>
           </apex:column>
           <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Item"  rerender="results,debug">
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!obj.PBE.Name}"/>
            </apex:column>
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Description"  rerender="results,debug">
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!obj.PBE.Product2.Description__c}"/>
            </apex:column>
             <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Product Type"  rerender="results,debug">
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!obj.PBE.Product2.Product_Type__c }"/>
            </apex:column>            
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="List Price"  rerender="results,debug">
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!obj.PBE.UnitPrice}"/>
            </apex:column>
        </apex:pageBlockTable>     
           <apex:outputPanel >
           <apex:commandButton value="<<Previous" action="{!previous}" rendered="{!hasPrevious}" reRender="results" />
           <apex:commandButton value="Next >>" action="{!next}" rendered="{!hasNext}" reRender="results" />
        </apex:outputPanel> 
    </apex:pageBlock>
    </td>
  </tr>
  </table>
<apex:pageBlock title="Selected Products" mode="edit">
	<apex:pageBlockTable value="{!selectedAccounts}" var="obj" id="block2">
      <table cellpadding="2" cellspacing="2">
      <tr>
      	<td>
            <apex:column value="{!obj.product2.Item__c}" />
      	</td>
      </tr>
             <apex:column value="{!obj.product2.Description__c}"/>
            <apex:column value="{!obj.Product2.Product_Type__c}"/>
            <apex:column value="{!obj.UnitPrice}"/>
            <apex:column value="{!obj.Quantity__c}"/>
      </table>
	</apex:pageBlockTable>
</apex:pageBlock> 
<!--
  <apex:pageBlock title="Debug - SOQL" id="debug">
      <apex:outputText value="{!debugSoql}" />   
      <!--apex:outputText value="{!QuoteId}" /-->  
       <!--apex:outputText value="{!QuantityProduct}" /-->  
      <!--apex:outputText value="{!Productcount}" /-->  
       <!--  <br></br> -->
      <!--apex:outputText value="{!sProductid}"/--> 
 <!--
 </apex:pageBlock> 
 -->

  </apex:pageBlock>
  </apex:form>
</apex:page>

and class
public class ContactSearchController7 {
 // the soql without the order and limit
  private String soql {get;set;}
      //coping it from class CustomPaginationDemoPBE
  public List<ProductWrapper> lstWrapper {get;set;}
  public List<ProductWrapper> lstSetController{get;set;}
  CustomIterablePBE obj;
  //copy done
  public integer QuantityProduct {get;set;}  
  private String QuoteNumber {get;set;}
  private String QuoteName {get;set;}
  private String OptyId {get;set;}
  //public String firstNameval{get;set;}
    //
  public list<wrapproduct> wrapproductList { get; set; }
  public list<PricebookEntry> selectedAccounts{get; set; }
  //GA 8/26/2015 commented- Code Coverage
  //this list is added by GA 8-17
  //The main purpose of this list is to inserts records in Quote Line Item
 /* Public List<QuoteLineItem> items{get; set; }
  public String QuoteId{
     get{return 'Quote#='+QuoteNumber +'  name:'+QuoteName+'   OptyId=' +OptyId;}
     set;
   }
*/
  // format the soql for display on the visualforce page
  public String debugSoql {
    get { return soql; }
    set;
  }
    /*
  public ApexPages.StandardSetController con { get; set; } 
*/
  public ContactSearchController7(ApexPages.StandardController controller) {
    wrapproductList = new list<wrapproduct>();
    selectedAccounts=new list<PricebookEntry>();
   //GA 8/26/2015 commented- Code Coverage
   // items=new list<QuoteLineItem>();
   //coping it from class CustomPaginationDemoPBE
    lstWrapper =  new List<ProductWrapper>();
    lstSetController = new List<ProductWrapper>();
    //copy done
   soql ='SELECT product2.Product_Type__c,product2.Description__c,product2.Item__c,product2.CCO_Standard_Cost__c ,name, ProductCode,UnitPrice,Quantity__c,select_product__c FROM PricebookEntry WHERE UnitPrice  IN (null)';
   QuoteNumber=System.currentPageReference().getParameters().get('id');
   QuoteName=System.currentPageReference().getParameters().get('name');
   OptyId=System.currentPageReference().getParameters().get('OpportunityId');
   runQuery();
  }
  // runs the actual query
  Public PageReference AddProduct(){
  return null;
  }
  public void runQuery() {
    try {
          
      soql=soql + ' limit 100';
      //wrapproductlist.clear();
       lstWrapper.clear();
        wrapproductlist.clear();
      //cleaning values in Con : Standard Set Controller
      //con=null;
      List<PricebookEntry> lstContact = Database.query(soql);
        
        for(PricebookEntry PBE : lstContact )
        {
            lstWrapper.add(new ProductWrapper(PBE ,false));
        }

        obj = new CustomIterablePBE (lstWrapper); 
        obj.setPageSize = 17;
        next();       

    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'+e));
    }
  }

  // runs the search with parameters passed via Javascript
  public PageReference runSearch() {
    String Name = Apexpages.currentPage().getParameters().get('Name'); 
    String Description= Apexpages.currentPage().getParameters().get('Description'); 
    String ProductType= Apexpages.currentPage().getParameters().get('ProductType'); 
    //GA added 9/9/2015
     // String Quantity =Apexpages.currentPage().getParameters().get('Quantity'); 
    /* Gaurav Commented 09/02
      soql = 'SELECT product2.Product_Type__c,product2.Description__c,Id,product2.Item__c,Name,product2.CCO_Standard_Cost__c,UnitPrice,Quantity__c,select_product__c FROM PricebookEntry where name != null';
       if (ProductType!=null)
    soql += ' and Product2.Product_Type__c LIKE \''+String.escapeSingleQuotes(ProductType)+'%\'';
        if (Description!=null)
    soql += ' and Product2.Description__c LIKE \''+String.escapeSingleQuotes(Description)+'%\'';
         if (Name!=null)
    soql += ' and name LIKE \''+String.escapeSingleQuotes(Name)+'%\''; 
    */
    //soql = 'SELECT ProductCode FROM Product2';
    if(ProductType.length()>1 || Description.length()>1 || Name.length()>1)
     {

        //if (ProductType==null && Description==null && Name==null)
        	//{
         	//	soql='SELECT product2.Product_Type__c,product2.Description__c,Id,product2.Item__c,Name,product2.CCO_Standard_Cost__c,UnitPrice,Quantity__c,select_product__c FROM PricebookEntry where name=null  and Product2.Product_Type__c=null and Product2.Description__c =null';
        	//}

        if (ProductType.length()>0 && Description.length()>0 && Name.length()==0)
            {
             	soql='SELECT product2.Product_Type__c,product2.Description__c,Id,product2.Item__c,Name,product2.CCO_Standard_Cost__c,UnitPrice,Quantity__c,select_product__c FROM PricebookEntry where Product2.Description__c LIKE \''+String.escapeSingleQuotes(Description)+'%\'' +' and Product2.Product_Type__c LIKE \''+String.escapeSingleQuotes(ProductType)+'%\'';
            }
        if (ProductType.length()>0 && Description.length()==0 && Name.length()==0)
            {
             soql='SELECT product2.Product_Type__c,product2.Description__c,Id,product2.Item__c,Name,product2.CCO_Standard_Cost__c,UnitPrice,Quantity__c,select_product__c FROM PricebookEntry where Product2.Product_Type__c LIKE \''+String.escapeSingleQuotes(ProductType)+'%\'';
            }
        if (ProductType.length()>0 && Description.length()>0 && Name.length()>0)
            {
             soql='SELECT product2.Product_Type__c,product2.Description__c,Id,product2.Item__c,Name,product2.CCO_Standard_Cost__c,UnitPrice,Quantity__c,select_product__c FROM PricebookEntry where Product2.Description__c LIKE \''+String.escapeSingleQuotes(Description)+'%\'' +' and Product2.Product_Type__c LIKE \''+String.escapeSingleQuotes(ProductType)+'%\'' +' and name LIKE \''+String.escapeSingleQuotes(Name)+'%\'';
             }
         if (ProductType.length()>0  && Name.length()>0 && Description.length() == 0)
            {
             soql='SELECT product2.Product_Type__c,product2.Description__c,Id,product2.Item__c,Name,product2.CCO_Standard_Cost__c,UnitPrice,Quantity__c,select_product__c FROM PricebookEntry where  Product2.Product_Type__c LIKE \''+String.escapeSingleQuotes(ProductType)+'%\'' +' and name LIKE \''+String.escapeSingleQuotes(Name)+'%\'';
             }
         if (ProductType.length() == 0 && Description.length() >0 && Name.length() >0)
            {
             soql='SELECT product2.Product_Type__c,product2.Description__c,Id,product2.Item__c,Name,product2.CCO_Standard_Cost__c,UnitPrice,Quantity__c,select_product__c FROM PricebookEntry where Product2.Description__c LIKE \''+String.escapeSingleQuotes(Description)+'%\''  +' and name LIKE \''+String.escapeSingleQuotes(Name)+'%\'';
             }
         if (ProductType.length() == 0 && Description.length() == 0 && Name.length() >0)
            {
             soql='SELECT product2.Product_Type__c,product2.Description__c,Id,product2.Item__c,Name,product2.CCO_Standard_Cost__c,UnitPrice,Quantity__c,select_product__c FROM PricebookEntry where name LIKE \''+String.escapeSingleQuotes(Name)+'%\'';
             }
     }//end if
     if (ProductType.length()==0 && Description.length()>0 && Name.length()==0)
       {
           soql='SELECT product2.Product_Type__c,product2.Description__c,Id,product2.Item__c,Name,product2.CCO_Standard_Cost__c,UnitPrice,Quantity__c,select_product__c FROM PricebookEntry where Product2.Description__c LIKE \''+String.escapeSingleQuotes(Description)+'%\'';
       }
    /*if (ProductType.length()>3)
        	{
         		soql='SELECT product2.Product_Type__c,product2.Description__c,Id,product2.Item__c,Name,product2.CCO_Standard_Cost__c,UnitPrice,Quantity__c,select_product__c FROM PricebookEntry where name=null  and Product2.Product_Type__c=null and Product2.Description__c =null';
        	}  
   */
    // run the query again
      if(ProductType.length()>1 || Description.length()>1 || Name.length()>1){
            runQuery();  
      }
     if (ProductType.length()==0 && Description.length()==0 && Name.length()==0){
            soql='SELECT product2.Product_Type__c,product2.Description__c,Id,product2.Item__c,Name,product2.CCO_Standard_Cost__c,UnitPrice,Quantity__c,select_product__c FROM PricebookEntry where name=null  and Product2.Product_Type__c=null and Product2.Description__c =null';
            runQuery();  
      }

    return null;
  }
  
   
   
    //### SELECTED PRODUCT SHOWN BY THIS METHOD
      public pagereference ProcessSelected(){
       //Apexpages.currentPage().getParameters().put ('Name',null); 
       //system.currentPageReference().getParameters().put('Name',null);  
       //GA Added 09/09/2015
        //String Quantity=Apexpages.currentPage().getParameters().get('Quantity');
      //QuantityProduct=  integer.valueOf(Quantity);
       integer sAccountCount=[SELECT count() FROM Quote WHERE Pelco_Account_Name__c != null AND Id =: QuoteNumber];
       String CustomerNumber='0';
       integer CustomerNumberCount;
       string AccountName;
       String ItemNumber='0';
       if (sAccountCount>0){
           Id AccountId= [SELECT Pelco_Account_Name__c FROM Quote WHERE Pelco_Account_Name__c != null AND Id =: QuoteNumber].Pelco_Account_Name__c;
            CustomerNumberCount=[SELECT count() from Account WHERE Id =: AccountId and AccountNumber != null ];
                if(CustomerNumberCount == 0){
                    AccountName=[SELECT name from Account where Id =: AccountId].name;
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Pricing not possible. Customer Number is null. Please add Customer Number for Account Name: '+AccountName));
                }
            if (CustomerNumberCount> 0){
            	CustomerNumber=[SELECT AccountNumber FROM Account WHERE Id =: AccountId].AccountNumber;
            	}
        }
        if (sAccountCount == 0){
           Id AccountId= [SELECT AccountId FROM Quote WHERE Pelco_Account_Name__c != null AND Id =: QuoteNumber].Pelco_Account_Name__c;
           CustomerNumber=[SELECT AccountNumber FROM Account WHERE Id =: AccountId].AccountNumber;
        }
     Integer Count=0;
          for(productwrapper wrapobj1:lstWrapper){
           if(wrapobj1.isSelected==true){
            Count=Count+1;}//end if
           }//end for
      if (Count > 5 ){
             ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please select 5 or less items at a time to add to Quote'));
             }//end if
     if(QuantityProduct> 0 && CustomerNumberCount>0 && Count<=5){ 
      //for(wrapproduct wrapobj:wrapproductlist){
		//count=wraprojectlist.isSelected.size();
         for(productwrapper wrapobj:lstWrapper){
           if(wrapobj.isSelected==true){
                        Integer ProductCount=[SELECT count() FROM QuoteLineItem WHERE Product2Id =: wrapobj.PBE.Product2.Id AND QuoteId =: QuoteNumber];
                       if (ProductCount == 0 ){
                              wrapobj.PBE.Quantity__c=QuantityProduct; 
                              selectedAccounts.add(wrapobj.PBE);
                               ItemNumber= wrapobj.PBE.Name;
                               QuoteLineItem pi= new QuoteLineItem();
                                     //double DealerPrice=wrapobj.PBE.UnitPrice;
                                     CalculatePelcoDiscount1 NewDiscount= new CalculatePelcoDiscount1();
                                     double sDiscount=NewDiscount.CalculatePelcoDiscount1(ItemNumber,CustomerNumber )*100;
                                     CalculatePelcoPrice newPrice=new CalculatePelcoPrice();
                                     double DealerPrice=newPrice.CalculatePelcoPrice(ItemNumber,CustomerNumber );
                                     string pelcoCurrency=newPrice.CalculatePelcoCurrency(CustomerNumber);
                                     //double DealerPrice=pelcoPrice;
                                     //double sDiscount=PelcoDiscount;
                                     //sDiscount=sDiscount*100;
                                    //QuoteLineItem QLI = new QuoteLineItem(QuoteId = QuoteNumber,PricebookEntryId=wrapobj.accn.Id,Product2Id=wrapobj.accn.Product2.Id ,Quantity = wrapobj.accn.Quantity__c, UnitPrice=wrapobj.accn.UnitPrice,discount=sDiscount);
                                     //Gaurav Added 9/2- Due to changes in percentage
                           			 sDiscount=sDiscount/100;
                                     QuoteLineItem QLI = new QuoteLineItem(Currency__c=pelcoCurrency,QuoteId = QuoteNumber,PricebookEntryId=wrapobj.PBE.Id,Product2Id=wrapobj.PBE.Product2.Id ,CCO_Standard_Cost__c =wrapobj.PBE.Product2.CCO_Standard_Cost__c,Quantity = QuantityProduct, UnitPrice=DealerPrice,Dealer_Price__c=DealerPrice, discount=sDiscount);
                                     insert QLI; 
                           			//QuantityProduct=null;
                                      //wrapobj.PBE.Quantity__c=null;
                                   /*Database.SaveResult[] lsr=Database.insert(new QuoteLineItem[]{QLI});
                                    for(Database.SaveResult sr: lsr){
                                    if(!sr.isSuccess()){
                                        Database.Error err = sr.getErrors()[0];
                                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Error in Insert'));
                                        }//end if sr
                                     }//end for
                                    */
                                   // populating and then adding data in the List
                                 /*  
                              		pi.Currency__c=pelcoCurrency;
	                          		pi.QuoteId = QuoteNumber;
	                          		pi.PricebookEntryId=wrapobj.PBE.Id;
	                          		pi.Product2Id=wrapobj.PBE.Product2.Id;
	                          		pi.Quantity = QuantityProduct; 
	                          		pi.UnitPrice=DealerPrice;
	                          		pi.Dealer_Price__c=DealerPrice; 
	                          		pi.discount=sDiscount;
                              items.add(pi);*/
                            }//end if ProductCount
                            if (ProductCount > 0 ){
                              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'You have already added '+wrapobj.PBE.name));
                           }//end if
                  // }//end if
                  /* */

           }//end if
			
         }//end for
         QuantityProduct=null;
        }//end if QuantityProduct> 0
      // inserting the records in Quote Items
      
      /* if(items.size() > 0 )
        {
            insert items;
        }   
       */
      if(QuantityProduct== 0){ 
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please Add the Qantity of Item'));
        } 
       return null;
      }//end function

   
    public PageReference BackToQuote(){
           string Oppty_Id=[SELECT OpportunityId FROM Quote WHERE Id =: QuoteNumber].OpportunityId;
           boolean AccntOpty=[SELECT Account_Opportunity__c FROM Opportunity WHERE Id =: Oppty_Id].Account_Opportunity__c;
           if (AccntOpty== true){
           return new PageReference('/apex/newquotepage?id='+QuoteNumber);
           }
           if (AccntOpty == false){
            return new PageReference('/'+QuoteNumber);
            }
            return new PageReference('/'+QuoteNumber);
         }
   
  public Boolean hasNext {
            get 
            {
                return obj.hasNext();
            }
            set;
        }
        
        public Boolean hasPrevious {
            get 
            {
                return obj.hasPrevious();
            }
            set;
        }
        
        public void next() 
        {
            lstSetController = obj.next();
        }
        
        public void previous() 
        {
            lstSetController = obj.previous();
        }
    

}

Regards, 
Gaurav
 
We would like to avoid to hardcode value in an apex class and use "environment variable". Is the use of custom settings the right way to do that ? 

Today I created a custom settings containing 2 fields, an url and a authorization token. The values are differents from one sandbox to another, so I create one data set for each of my sandbox (dev-int-uat-prod). Now my problem is to know in wich sandbox am I ? To retrieve the right values from my custom setting and of course I don't want to hardcode it. I used UserInfo.getUserName().substringAfterLast('@').substringAfterLast('.') to retrieve the sandbox name but for production this code doesn't work, so can anyone help me on the best way to do that ?

Thanks in advance for your answers and your help.
Hi all, I have One custome field i.e. Hotel_Started_Date__C and i have another field i.e. Number_Of_Years__C. So, i need to get total years in between old date and Today date. For Example, if i enter "01/01/2000" in Hotel_Started_Date__C. It's need to calculate old date(01/01/2000) -  today date(09/09/2015) = 15 years. That 15 years nee to store in Number_Of_Years__C.

Note : Using Triggers

Thanks in advance
Thulasi
Hi, I need test class for below controller.

public class Sum
{
 public integer first { get; set;}
  public integer second { get; set;}
  public integer result {get; set;}
  public void add()
  {
   result = first + second ;
  }
 public void sub()
  {
   result = first - second ;
   }
 public void mul()
  {
   result = first * second ;
   }
public void mod()
 {
   result = first / second ;
 }
  }
How to update update all record of object when one record changed    .....
Hai,
I have writter a trigger on custom obj called as Horticulture__c to avoid duplicate entries/names in the table. While executing my trigger it shows error like "Initial term of field expression must be a concrete SObject: List<Horticulture__c>". pls give solution.
trigger Duplicate_Farmer_Horti on Horticulture__c (before insert,before update)
{
    for (Horticulture__c H:Trigger.New)
    {
        List<Horticulture__c> Horti = [select id from Horticulture__c where Applicant_Name__c=:H.Applicant_Name__c];
        if(Horti.size()>0)
        {
            Horti.Applicant_Name__c.addError('You can not create duplicate name');
        }            
        
    }

}
I am running into this issue, I have fixed it before by adding a boolean but even with it on this example I still get the same error. It's throwing the error on line 52. 
 
public class Account_HDL {

private static boolean updatecstimp = false;
private static boolean dontupdatecstimp = false;
private static boolean newreview = false;
    
    
public static void UpdateCSTImp(Account[] acc){
list<CST_Implementation__c> cstimplist = new List<CST_Implementation__c>();
Set<String> cstimpIds = new Set<String>();
list<Account> updateacclist = new List<Account>();
Set<String> updateaccIds = new Set<String>();


    
    for(Account accs : acc){
        //updateaccIds.add(accs.Id);
        updateacclist  = [select Id, CST_Fully_Implemented_On__c, CST_Implementation_Stage__c, Days_from_RC_to_Imp__c, Last_Review_Date__c, 
                 Number_of_CST_Implemented_Services__c, Number_of_CST_Imp_Services_Complete__c, Number_of_CST_Imp_Services_Not_Complete__c, 
                 Latest_CST_Implementation__c, Regarding_Annual_Review__c, Review_FP_Result__c, Review_ROA_Result__c, Review_Super_Result__c 
                 from Account where Id =: trigger.new];
        
            Account oldAcc = (Account)Trigger.oldMap.get(accs.Id);
        
        for(Account updateacc : updateacclist){
           if(oldAcc.Regarding_Annual_Review__c != accs.Regarding_Annual_Review__c && accs.Regarding_Annual_Review__c != null
              && dontupdatecstimp == false && newreview == false){
               dontupdatecstimp = true;
               updateacc.CST_Fully_Implemented_On__c  = null;
               updateacc.CST_Implementation_Stage__c  = ''; 
               updateacc.Last_Review_Date__c  = null; 
               updateacc.Number_of_CST_Implemented_Services__c  = null; 
               updateacc.Number_of_CST_Imp_Services_Complete__c  = null; 
               updateacc.Number_of_CST_Imp_Services_Not_Complete__c  = null; 
               updateacc.Review_FP_Result__c  = ''; 
               updateacc.Review_ROA_Result__c  = ''; 
               updateacc.Review_Super_Result__c  = ''; 
               //create new cst imp for annual review   
                            List<CST_Implementation__c> addcstimplist = new list<CST_Implementation__c>();
                           for(CST_Implementation__c newcstimp : addcstimplist){
                            
                            addcstimplist.add(new CST_Implementation__c(
                            Name = 'Annual Review',
                            Related_Account__c = updateacc.Id
                            ));
                           }
                           insert addcstimplist;
                        
            }
           }
             if(updateacclist.size()>0 && dontupdatecstimp == true && newreview == false){
                update updateacclist;
                newreview = true;
               } 
        cstimpIds.add(accs.Latest_CST_Implementation__c);
        cstimplist = [select Id  from CST_Implementation__c where ID in : cstimpIds];
        for(CST_Implementation__c relatedcstimp : cstimplist){
            if(dontupdatecstimp == false){
            if( oldAcc.CST_Fully_Implemented_On__c != accs.CST_Fully_Implemented_On__c){
                relatedcstimp.CST_Fully_Implemented_On__c = accs.CST_Fully_Implemented_On__c;
                updatecstimp = true;
            }
            if( oldAcc.CST_Implementation_Stage__c != accs.CST_Implementation_Stage__c){
                relatedcstimp.CST_Implementation_Stage__c = accs.CST_Implementation_Stage__c;
                updatecstimp = true;
            }
            if( oldAcc.Last_Review_Date__c != accs.Last_Review_Date__c){
                relatedcstimp.Last_Review_Date__c = accs.Last_Review_Date__c;
                updatecstimp = true;
            }
            if( oldAcc.Number_of_CST_Implemented_Services__c != accs.Number_of_CST_Implemented_Services__c){
                relatedcstimp.Number_of_CST_Implemented_Services__c = accs.Number_of_CST_Implemented_Services__c;
                updatecstimp = true;
            }
            if( oldAcc.Number_of_CST_Imp_Services_Complete__c != accs.Number_of_CST_Imp_Services_Complete__c){
                relatedcstimp.Number_of_CST_Imp_Services_Complete__c = accs.Number_of_CST_Imp_Services_Complete__c;
                updatecstimp = true;
            }
            if( oldAcc.Number_of_CST_Imp_Services_Not_Complete__c != accs.Number_of_CST_Imp_Services_Not_Complete__c){
                relatedcstimp.Number_of_CST_Imp_Services_Not_Complete__c = accs.Number_of_CST_Imp_Services_Not_Complete__c;
                updatecstimp = true;
            }
            if( oldAcc.Review_FP_Result__c != accs.Review_FP_Result__c){
                relatedcstimp.Review_FP_Result__c = accs.Review_FP_Result__c;
                updatecstimp = true;
            }
            if( oldAcc.Review_ROA_Result__c != accs.Review_ROA_Result__c){
                relatedcstimp.Review_ROA_Result__c = accs.Review_ROA_Result__c;
                updatecstimp = true;
            }
            if( oldAcc.Review_Super_Result__c != accs.Review_Super_Result__c){
                relatedcstimp.Review_Super_Result__c = accs.Review_Super_Result__c;
                updatecstimp = true;
            }
            }
        } 
        if(cstimplist.size()>0 && updatecstimp == true && dontupdatecstimp == false){
        update cstimplist;
        }
    }
       
}
}

 
I created a trigger on Quote
trigger updateOpptyAccount on Quote (before insert,before update) {
    for (Quote QuoteInLoop : Trigger.new){
       // if(QuoteInLoop.Opportunity.name != '.'){
        Boolean sMainAccount=QuoteInLoop.Main_Account__c;
        String sMainAccountId=QuoteInLoop.AccountId;
        String sQuoteAccountId=QuoteInLoop.Pelco_Account_Name__c;
        String sQuotePriceBook=QuoteInLoop.PriceBook2Id;
        String sQuoteId=QuoteInLoop.Id;
        String sOptyId=QuoteInLoop.OpportunityId;
        //checking if price book is attached to the quote
        //if no price book exist than defaulting the standard price book
        if(sQuotePriceBook == null)
        {
            QuoteInLoop.Pricebook2Id =[SELECT Id FROM Pricebook2 WHERE Name = 'Standard Price Book' LIMIT 1].Id;
        }
       
        //if pelco quote account is null
        if (sQuoteAccountId == null)
        {
            QuoteInLoop.Pelco_Account_Name__c=sMainAccountId;
            sQuoteAccountId=sMainAccountId;
        }
        //if pelco quote account is not null
        if (sQuoteAccountId != null)
        {    
            if(sMainAccountId <>sQuoteAccountId)
              {
               //make sure pelco account is not added to opportunity
               Integer iPelAccnt1=[SELECT count() FROM Pelco_Account__c WHERE AccountName__c = :sQuoteAccountId AND OpportunityName__c =:sOptyId ];
               if(iPelAccnt1 == 0)
                 {
                      // Inserting a new Pelco Account
                      String sAccountName=[SELECT Name FROM Account WHERE Id = :sQuoteAccountId].Name;
                      List <Pelco_Account__c > PelcoAccountLst =new List <Pelco_Account__c>();
                      Pelco_Account__c PelAcc1= new Pelco_Account__c();
                      PelAcc1.OpportunityName__c=sOptyId;
                      PelAcc1.AccountName__c=sQuoteAccountId;
                      PelAcc1.Name=sAccountName;
                      PelcoAccountLst.add(PelAcc1);
                      insert PelcoAccountLst;  
                  }//closing if for iPelAccnt1 
             }//end if
        }//end if 
             
     }//closing forLoop
 }//closing trigger updateOpptyAccount

The test class is 
@istest
private class TestUpdateOptyAccount {
    static testMethod void TestOptyUpdate() {
        //Create Account
        Account a = new Account();
    	a.Name = 'Ritzy';
    	insert a;
        
        //Create Opportunity
        Opportunity opty=new Opportunity();
		opty.Name='Test Opportunity';
        opty.StageName='Prospecting';
        opty.CloseDate=date.valueof('2015-09-10');
        opty.AccountId=a.Id;
        //opty.Pelco_Account_Name__c=PA.id;
		Insert opty; 
        
        //Create pelco account
        Pelco_Account__c PA =new Pelco_Account__c();
        PA.Name='Ritzy';
        //PA.OpportunityId=Opty.id; 
        PA.AccountName__c=a.Id;
        PA.OpportunityName__c=Opty.id;
        Insert PA;
         //Insert Quote
        Quote q =new Quote();
         q.name='Test Quote';
         q.opportunityId=opty.id;
        insert q;
        
    }
}

The trigger is failing with error message :
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, updateOpptyAccount: execution of BeforeInsert

caused by: System.QueryException: List has no rows for assignment to SObject

Trigger.updateOpptyAccount: line 14, column 1: []
I just inserted a record. why would system complain that I have no rows for assignment to SObject i.e. Quote

Line 14 is 
QuoteInLoop.Pricebook2Id =[SELECT Id FROM Pricebook2 WHERE Name = 'Standard Price Book' LIMIT 1].Id;


 
My requirement was Latest opportunity name should be displayed in account object custom field.

Getting null pointer exception when I delete the opportunity for the Account. How do we handle this error.

Class :

public class OppAccUpdate
{
  
  public void oppupdate(List<opportunity> oplist)
  {
      
    set<id> accid = new set<id>();
    
   // List<Account> acctoUpdate= new List<Account>();
   
   Map<id,Account> mapaccounts = new Map<id,Account>();
    
    for(opportunity opp:oplist)
    {
       accid.add(opp.Accountid);
    }
    List<Account> acc =[select id, oppname__c,(select id, name from opportunities order by createddate) from Account where id in:accid];
    system.debug('****Thesize of account***'+acc.size());
    system.debug('****The oppname***'+acc[0].oppname__c);
    system.debug('****The opportunity***'+acc[0].opportunities);
    for(Account a:acc)
    {
       for(opportunity o:a.Opportunities)
       {
          if(a.oppname__c==null || (a.oppname__c!=o.Name))
          {
          system.debug('***inside for loop***'+ a.oppname__c);
          system.debug('***inside for loop111***'+ o.name);
          a.oppname__c = o.Name;
          mapaccounts.put(a.id,a);
         // acctoUpdate.add(a);
          }
       }
    }
    if(!mapaccounts.isEmpty())
    update  mapaccounts.values();

      
  }
}

Trigger:

trigger oppaccupdate on Opportunity (after insert, After update, After delete) 
{
     Opportunity[] opp = trigger.new;
     
     if(trigger.isInsert || trigger.isAfter)
     {
       OppAccUpdate ou = new OppAccUpdate();
       ou.oppupdate(opp);
     }
     
      if(trigger.isUpdate || trigger.isAfter)
     {
       OppAccUpdate ou = new OppAccUpdate();
       ou.oppupdate(opp);
     }
     
      if(trigger.isDelete || trigger.isAfter)
     {
       Opportunity[] opp1 = trigger.old;
       OppAccUpdate ou = new OppAccUpdate();
       ou.oppupdate(opp1);
     }
}
Code Piece A

Account[] accs = [Select .... from Account where ... Limit 30000];
Account[] accsToUpdate = new Account[]{};
for (Account acc: accs) {
if (...) {
accsToUpdate.add(acc);
}
}

update accsToUpdate;


Code Piece B
Account[] accsToUpdate = new Account[]{};
for (Account acc: [Select .... from Account where ... Limit 30000]) {
if (...) {
accsToUpdate.add(acc);
}
}

update accsToUpdate;

For code priece A, I know there is a risk of running into heap size limit because of saving big data into array; what about code priece B? Will SFDC user QueryMore to implement the for loop in which data fetched later on could override data fetched previously and saved in heap?
Hi,
Need salesforce project support in california timings. Intrested please respond.

Thanks,