• abhishek singh 497
  • NEWBIE
  • 135 Points
  • Member since 2019

  • Chatter
    Feed
  • 4
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 3
    Questions
  • 48
    Replies
Hi Everyone,

I created a Batch apex to process bulk records. Once the batch process is completed then need to send an email alert. For that, I implemented the following logic on the finish method.
//Query the AsyncApexJob object to retrieve the current job's information.
AsyncApexJob apexJob = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email
FROM AsyncApexJob WHERE Id =: BC.getJobId()];
            
//Send an email to the Apex job's submitter notifying of job completion.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddress = new String[] {apexJob.CreatedBy.Email};
mail.setToAddresses(toAddress);
mail.setSubject('Apex Job status is ' + apexJob.Status);
mail.setPlainTextBody('The batch Apex job processed ' + apexJob.TotalJobItems + ' batches with '+ apexJob.NumberOfErrors + ' failures.');
Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {mail};
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);

But I didn't get the email alert.
I verified the debug logs, it displays the following message.

|results|"common.apex.runtime.impl.ScalarList@bac8ad2"|0x1ef0e446.
Can anyone please help me.
Thanks in advance.
 
Hello,

I have below error:
Maximum CPU time on the Salesforce servers

What are possible workarounds ?
Create an Apex class called 'AddPrimaryContact' that implements the Queueable interface.
Create a constructor for the class that accepts as its first argument a Contact sObject and a second argument as a string for the State abbreviation.
The execute method must query for a maximum of 200 Accounts with the BillingState specified by the State abbreviation passed into the constructor and insert the Contact sObject record associated to each Account. Look at the sObject clone() method.
Create an Apex test class called 'AddPrimaryContactTest'.
In the test class, insert 50 Account records for BillingState "NY" and 50 Account records for BillingState "CA". Create an instance of the AddPrimaryContact class, enqueue the job and assert that a Contact record was inserted for each of the 50 Accounts with the BillingState of "CA".
public with sharing class NumberOfAccountsRelatedToUser {

	public static void triggerHandler( System.TriggerOperation triggerEvent , list<Account> newAccounts, List<Account> oldAccounts) {

		Set<ID> related_user_IDs = new Set<ID>();

		if(triggerEvent == TriggerOperation.AFTER_INSERT){
			for(Account a: newAccounts){
				related_user_IDs.add(a.SDR_Owner__c);
				related_user_IDs.add(a.OwnerID);
			}
		}
		if(triggerEvent == TriggerOperation.AFTER_UPDATE){
			for(Account a: newAccounts){
				related_user_IDs.add(a.SDR_Owner__c);
				related_user_IDs.add(a.OwnerID);
			}
			for(Account a: oldAccounts){
				related_user_IDs.add(a.SDR_Owner__c);
				related_user_IDs.add(a.OwnerID);
			}
		}

		if(triggerEvent == TriggerOperation.AFTER_DELETE){
			for(Account a: oldAccounts){
				related_user_IDs.add(a.SDR_Owner__c);
				related_user_IDs.add(a.OwnerID);
			}
		}

		// now we want to say hey, we have these User ID's
		// lets go found how many accounts in which they are the SDR Owner and Account Owner


		List<AggregateResult> related_user_prospect_accounts = [SELECT COUNT(ID) sdr_owner_accounts, SDR_Owner__c FROM Account WHERE SDR_Owner__c in :related_user_IDs and (type ='Prospect - Being Worked' OR type='Prospect - Open' ) GROUP BY SDR_Owner__c];
		List<AggregateResult> related_user_owner_prospect_accounts = [SELECT COUNT(ID) owner_accounts, OwnerID FROM Account WHERE OwnerID in :related_user_IDs and (type ='Prospect - Being Worked' OR type='Prospect - Open' ) GROUP BY OwnerId];


		Map<Id, List<Integer>> userID_And_num_of_accounts = new Map<Id, List<Integer>>();

		// we are assuming there will always be an account owner
		// which is definitely a fine assertion, because an account cannot be created without an owner
		for(AggregateResult ar: related_user_owner_prospect_accounts){
		    ID owner_ID = (ID)ar.get('OwnerID');

		    // check if Id is in Map, only initialize new list if ID not in map
		    if(!userID_And_num_of_accounts.containsKey(owner_ID)){
		        userID_And_num_of_accounts.put(owner_ID, new List<Integer>());
		    }

		    userID_And_num_of_accounts.get(owner_ID).add((Integer)ar.get('owner_accounts'));
		
		}



		for(AggregateResult ar: related_user_prospect_accounts){
		    ID sdr_owner_ID = (ID)ar.get('SDR_Owner__c');

		    // check if Id is in Map, only initialize new list if ID not in map
		    if(!userID_And_num_of_accounts.containsKey(sdr_owner_ID)){
		        userID_And_num_of_accounts.put(sdr_owner_ID, new List<Integer>());
		    }

		    if(sdr_owner_ID == null){
		    	continue;
		    }
		    else{
		    	// add the number of sdr accounts to that IDs map
		    	userID_And_num_of_accounts.get(sdr_owner_ID).add((Integer)ar.get('sdr_owner_accounts'));
		    }

	
		}


		// now we want to update the users field
		List<ID> user_IDs = new List<ID>();

		for(ID user_ID: userID_And_num_of_accounts.keySet()){
			user_IDs.add(user_ID);
		}

		// now we want to get the actual user object
		List<User> users = [SELECT ID, SDR_Owner_Prospect__c , Account_Owner_Prospect__c FROM User WHERE ID in :user_IDs];


		List<User> users_to_update = new List<User>();
		for(User u: users){
			List<Integer> sdr_and_owner_accounts = userID_And_num_of_accounts.get(u.ID);			
			if(sdr_and_owner_accounts.size() == 1){
				u.Account_Owner_Prospect__c = sdr_and_owner_accounts[0];
				u.SDR_Owner_Prospect__c = 0;
			}
			else{
				u.Account_Owner_Prospect__c = sdr_and_owner_accounts[0];
				u.SDR_Owner_Prospect__c = sdr_and_owner_accounts[1];	
			}

			users_to_update.add(u);
		}

		update users_to_update;

	}


}

What is going on with this trigger. All I am trying to do is update two user fields when the trigger fires.
Hello Team,
 I have json data of account and contact and want to insert the same into the salesforce, So I have made Restapi using wrapper class method.I am pasting JSON data, apex class.Please let me know what more things i need to change in my code.

Json data:-
{
  "accountList": [
    {
      "Name": "testPlC",
      "ActivationDate": "2011-10-04T16:58:54.858Z",
      "ContactItems": [
        {
          "FirstName": "PLCTest",
          "LastName": "plsignore",
          "Birthdate": "2011-10-04"
        },
        {
          "FirstName": "PLCTestv2",
          "LastName": "plsignorev2",
          "Birthdate": "2011-10-04"
        }
      ],
      "AccountNumber": "001"
    },
    {
      "Name": "testPlCV2",
      "ActivationDate": "2011-10-05T16:58:54.858Z",
      "ContactItems": [
        {
          "FirstName": "PLCTestv3",
          "LastName": "plsignore",
          "Birthdate": "2011-10-04"
        },
        {
          "FirstName": "PLCTestv4",
          "LastName": "plsignorev2",
          "Birthdate": "2011-10-04"
        }
      ],
      "AccountNumber": "002"
    }
  ]
}
Json class:-

public class JSON2Apex {
    public class AccountList{
        public String Name;
        public Date ActivationDate;
        public String AccountNumber;
        public List<ContactItems> ContactItems;   
    }
    public class ContactItems{
        public String FirstName;
        public String LastName;
        public String Birthdate;    
    }
    public List<AccountList> accountList;
    public static JSON2Apex parse(String json){
        return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);
    }
}

RestApi class:-
@RestResource(urlMapping='/Account/*')
public class AcctContactInsert {
    public static void listAcctContactInsert(){
        HttpResponse httpResponse;
        try{
            String endpoint ='';
            Http http = new Http();
            HttpRequest httpRequest = new HttpRequest();
            httpRequest.setMethod('GET');
            httpRequest.setEndpoint(endpoint);
            httpResponse = http.send(httpRequest);
            if(httpResponse.getStatusCode() == 200){
                String strResponse = httpResponse.getBody();
                JSON2Apex jsonApex = JSON2Apex.parse(strResponse);
                for(JSON2Apex.AccountList acctList : jsonApex.accountList){
                    System.debug('AccountList:'+acctList.Name+':'+acctList.ContactItems);  
                }
            }
        }
        catch(Exception ex){
            System.debug('Status Code: ' + httpResponse.getStatusCode());
            System.debug('Status Response: ' + httpResponse.getStatus()); 
        }
    }  
}
 
Hello Team,
I have one requirement where I need to compare old and new value of formula field in apex trigger.
Anyone has any suggestions or code please let me know.

Thanks 
Hello Team,
I am working on Community and I had one requirement where on contact email change, email of user and username also changes.
I have done this with the help of trigger and it's perfectly working fine. So what I have add-on requirement that user whose email has been changed should get some confirmation email.
I have read some blogs where there is no such standard functionality by salesforce as far now like when the inactive user becomes active he gets
"welcome to the community email"  
Do we have any workaround for it or someone has encountered a scenario like this? Please share your inputs.

 
Whenever a new transaction is performed successfully then update the customer object balance field based on 
     If Transaction Type=Deposit, Balance= balance +amount ;  withdraw balance= balance-amount;
     Note: Customers and Transaction has lookup Detail Relation.
Help Me With Simple Code.
 Whenever  a new contact is created for account, update the  corresponding account phone with the new contact phone field.
Hello Team,
 I have json data of account and contact and want to insert the same into the salesforce, So I have made Restapi using wrapper class method.I am pasting JSON data, apex class.Please let me know what more things i need to change in my code.

Json data:-
{
  "accountList": [
    {
      "Name": "testPlC",
      "ActivationDate": "2011-10-04T16:58:54.858Z",
      "ContactItems": [
        {
          "FirstName": "PLCTest",
          "LastName": "plsignore",
          "Birthdate": "2011-10-04"
        },
        {
          "FirstName": "PLCTestv2",
          "LastName": "plsignorev2",
          "Birthdate": "2011-10-04"
        }
      ],
      "AccountNumber": "001"
    },
    {
      "Name": "testPlCV2",
      "ActivationDate": "2011-10-05T16:58:54.858Z",
      "ContactItems": [
        {
          "FirstName": "PLCTestv3",
          "LastName": "plsignore",
          "Birthdate": "2011-10-04"
        },
        {
          "FirstName": "PLCTestv4",
          "LastName": "plsignorev2",
          "Birthdate": "2011-10-04"
        }
      ],
      "AccountNumber": "002"
    }
  ]
}
Json class:-

public class JSON2Apex {
    public class AccountList{
        public String Name;
        public Date ActivationDate;
        public String AccountNumber;
        public List<ContactItems> ContactItems;   
    }
    public class ContactItems{
        public String FirstName;
        public String LastName;
        public String Birthdate;    
    }
    public List<AccountList> accountList;
    public static JSON2Apex parse(String json){
        return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);
    }
}

RestApi class:-
@RestResource(urlMapping='/Account/*')
public class AcctContactInsert {
    public static void listAcctContactInsert(){
        HttpResponse httpResponse;
        try{
            String endpoint ='';
            Http http = new Http();
            HttpRequest httpRequest = new HttpRequest();
            httpRequest.setMethod('GET');
            httpRequest.setEndpoint(endpoint);
            httpResponse = http.send(httpRequest);
            if(httpResponse.getStatusCode() == 200){
                String strResponse = httpResponse.getBody();
                JSON2Apex jsonApex = JSON2Apex.parse(strResponse);
                for(JSON2Apex.AccountList acctList : jsonApex.accountList){
                    System.debug('AccountList:'+acctList.Name+':'+acctList.ContactItems);  
                }
            }
        }
        catch(Exception ex){
            System.debug('Status Code: ' + httpResponse.getStatusCode());
            System.debug('Status Response: ' + httpResponse.getStatus()); 
        }
    }  
}
 

In Account object we have a field called opportunity status and in opportunity object we have a field called 
Stage so when stage value will change the new value should display in the 
Account object field called opportunity status using trigger.
trigger trgcpundelete on Opportunity(after undelete)
 {
     set<id>oppid= new set<id>();
     if(trigger.isafter&&trigger.isundelete)
      {
         FOR(Opportunity o : trigger.new)
         {
          oppid.add(o.id);
         }
      }  
     list <Customer_Project__c> cplist = [select id,name,Opp_relation__c from Customer_Project__c where isdeleted=true and Opp_relation__c IN:oppid];
     undelete cplist;
}
Hi Everyone,

I created a Batch apex to process bulk records. Once the batch process is completed then need to send an email alert. For that, I implemented the following logic on the finish method.
//Query the AsyncApexJob object to retrieve the current job's information.
AsyncApexJob apexJob = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email
FROM AsyncApexJob WHERE Id =: BC.getJobId()];
            
//Send an email to the Apex job's submitter notifying of job completion.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddress = new String[] {apexJob.CreatedBy.Email};
mail.setToAddresses(toAddress);
mail.setSubject('Apex Job status is ' + apexJob.Status);
mail.setPlainTextBody('The batch Apex job processed ' + apexJob.TotalJobItems + ' batches with '+ apexJob.NumberOfErrors + ' failures.');
Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {mail};
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);

But I didn't get the email alert.
I verified the debug logs, it displays the following message.

|results|"common.apex.runtime.impl.ScalarList@bac8ad2"|0x1ef0e446.
Can anyone please help me.
Thanks in advance.
 
Hi, 

   In below code class CaseTriggerUtils
 
trigger CaseTrigger on Case (Before Insert, Before Update,After Insert, After Update){


   if(Trigger.isBefore) {
      CaseTriggerUtils.CaseUtils(Trigger.new);     
   } 
      

}
There is a error in line  
Map<Id, case> c = new Map<Id, case>([select id, casenumber,subject,createddate,ownerid,owner.name from case where subject like :('%' + CaseSubject + '%') order by createddate asc limit 10]);

When i try to update the case i am getting below error. 

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger CaseTrigger caused an unexpected exception, contact your administrator: CaseTrigger: execution of BeforeUpdate caused by: System.QueryException: Non-selective query against large object type (more than 200000 rows). Consider an indexed filter or contact salesforce.com about custom indexing. Even if a field is indexed a filter might still not be selective when: 1. The filter value includes null (for instance binding with a list that contains null) 2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times): Class.CaseTriggerUtils.CaseUtils: line 31, column 1
public class CaseTriggerUtils {

 public static void CaseUtils(List<Case> newLst) {  
  
  String FWSubject;
  String RWSubject;
  String CaseSubject;
  
    for (Case c : newLst) {
       system.debug('Case Number :' + c.casenumber); 
       system.debug('Case Subject : ' + c.subject);
       system.debug('Case Subject length : ' + c.subject.length());
       system.debug('Case Owner Name : ' + c.owner.name);
       
       CaseSubject = c.subject;
       
       //Search for FW and RW key word were length of the subject is more than 18
        if(c.subject != null && c.subject.length() > 18){
            if(!c.subject.Contains('FW:')){
              FWSubject = c.subject.replaceAll('FW:','');
              System.debug('FQ Trim String :' + FWSubject);     
         }  
    
        if(!c.subject.Contains('RW:')){ 
         RWSubject = c.subject.replaceAll('RW:','');
         System.debug('RW Trim String :' + RWSubject);   
         }     
       }  
     }
     
   Map<Id, case> c = new Map<Id, case>([select id, casenumber,subject,createddate,ownerid,owner.name from case where subject like :('%' + CaseSubject + '%') order by createddate asc limit 10]);
   
     
   //Search for same case based on subject within 10days. 
   /* list<case> ctendays = [select id, casenumber,subject,createddate,ownerid,owner.name from case where subject like :('%' + CaseSubject + '%') order by createddate asc limit 10];

   for(case ctndays : ctendays){
      system.debug('Existing Cases :'  + ctndays.casenumber + ' ' + ctndays.subject + ' ' + ctndays.createddate + ' ' + ctndays.owner.name);      
   }  */
  
  }

}

 
  • February 14, 2019
  • Like
  • 0
Hello,

I have below error:
Maximum CPU time on the Salesforce servers

What are possible workarounds ?

So I have the inputField:

<apex:inputField id="timeLimiter" value="{!pageForm.currentContract.ContractingVehicleRegistrationDate__c}" rendered="{!NOT(contractFieldReadOnlyRegistrationDate)}"/>


This is my inputField with the id='timeLimiter'  and I want to use my function only for this field.

My function is:

<script type="text/javascript">
	$j(document).ready(function () {
	    var today = new Date();
        var startYear=today.getFullYear()-19;
        var endYear=today.getFullYear();
        var optionsString='';
         if(startYear<endYear){
           for(var startCounter = startYear;startCounter<endYear; startCounter++){
			 optionsString += "<option value=\""+startCounter+"\">"+startCounter+"</option>";
	       }
		  $j('#calYearPicker').html(optionsString);}
    });
	</script>

The thing is I want my function to only apply to this field because in my form I have multiple fields of the same type(Date) and this function applies to all my fields(which I don't want ).

How can I pass my id from my field to my function?

Hi All,

 I am trying to update the account upon lead update.
Need help to optimize my code. Just want to avoid multiple for loops.

public class LeadAfterUpdateHandler {
    
    public static void updateRelatedAccount(List<Lead> newLeads, Map<Id,Lead> LeadOldMap){
        List<Lead> ChangedLeads = new List<Lead>();
        Map<String,String> LeadAccFieldsMap = new Map<String,String>();
        List<Account> accList = new List<Account>();
        List<Lead_to_Account_Sync__c> csList = [Select Id,Account_Field_Name__c,Lead_field_Name__c from Lead_to_Account_Sync__c];
        for(Lead_to_Account_Sync__c cs : csList){
           
            LeadAccFieldsMap.put(cs.Lead_field_Name__c,cs.Account_Field_Name__c) ;  
            }
        }
        for(Lead l : newLeads){
            for(String cs1 : LeadAccFieldsMap.keySet()){
                if(l.get(cs1) != LeadOldMap.get(l.id).get(cs1)){
                    ChangedLeads.add(l);
                    break;
                }
            }
        }
        
        for(Lead l : ChangedLeads){
            Account a = new Account(Id = l.Account_Id__c);
            a.Name = (String)l.get('LastName');
            for(String cs1 : LeadAccFieldsMap.keySet()){
                
                a.put(LeadAccFieldsMap.get(cs1),(String)l.get(cs1));
                system.debug('for a :::' + a);
            }
            system.debug('a:::' + a);
            accList.add(a);
            
        }
        
        if(accList.size() > 0){
            update accList;
        }
    }

}
Thanks,
Sirisha
Hello, 
I am trying to rollup a custom field "Product_Alert_Message" from the OpportunityItemLine to an Opportunity field "Product_Alerts_Roll_up__c".
I have the below Apex Class:
global with sharing class OppProductReqRollupTriggerHandler 
{
    global static void MainProcess(set<id> OpportunityIds)
    {
        //Create List to hold final concatenated result
        List<Opportunity> OpportunityList = new List<Opportunity>();
        
         //Create list to Children that have Parents within Parent Set.
        List<Opportunity> Opportunity = [Select Id,Product_Alerts_Roll_up__c, (SELECT Id,   OpportunityLineItem.Product_Alert_Message__c from OpportunityLineItem) from Opportunity where Id in :OpportunityIds];
 
        //Loop through List result to build concatenated string and add to sampleList
        for (Opportunity s:Opportunity)
        {
           String concatenateString = '';
              for (OpportunityLineItem sp: s.OpportunityLineItem)
              {
                if(sp.OpportunityLineItem__r.Product_Alert_Message__c <> null)
                {
                    concatenateString += sp.OpportunityLineItem__r.Product_Alert_Message__c + ';';
                }
              }
              s.Product_Alerts_Roll_up__c = concatenateString.replace('null','').removeEnd(';');
              OpportunityList.add(s);
        }
 
        //Update Parent object with concatenated string
        update OpportunityList;
    }
}
 but it's giving me the below errors:
Error: Compile Error:
OpportunityLineItem.Product_Alert_Message__c from OpportunityLineItem) from Opportunity
^
ERROR at Row:1:Column:102
Didn't understand relationship 'OpportunityLineItem' in FROM part of query call. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names. at line 9 column 41.
Can someone help me with this?
Thanks,
Please help me in updating the trigger code ,
Requirement is If the record is first created based on created date then set the checkbox as true.

trigger updateForecastMassUIpdateFields on ForecastSchedule__c (before insert, before update) {

for (ForecastSchedule__c fs:trigger.new)
    {
        /*List<Period> p=[SELECT Number , FiscalYearSettings.Name  FROM Period WHERE Type = 'Month' AND StartDate <=: fs.date__c AND EndDate >=: fs.date__c];   
    
        for(Period p1:p)
        {
            fs.fiscal_period__c=p1.number + '-' + p1.FiscalYearSettings.Name;
        }
        for ( Case c1 : [select id, name from case where id in (<ids>) ])

        {

        }*/
        if(fs.IsBudget__c==true || fs.SourceType__c=='4 - Budget')  
        {
            if(fs.Budget_Quantity__c==0 || fs.Budget_Quantity__c==null)
            {
                fs.Budget_Unit_Price__c=fs.UnitPrice__c;
                fs.Budget_Quantity__c=fs.Quantity__c;
                fs.Budget_Revenue__c=fs.Revenue__c;
                fs.Budget_Revenue_in_EUR__c=fs.RevenueInEUR__c;
            }
            else
            {
                fs.UnitPrice__c=fs.Budget_Unit_Price__c;
                fs.Quantity__c=fs.Budget_Quantity__c;
                //fs.Revenue__c=fs.Budget_Revenue__c;
                //fs.RevenueInEUR__c=fs.Budget_Revenue_in_EUR__c;
            }
         List<ForecastSchedule__c> FSList=[Select Id,Name,FC_quantity__c,FC_Revenue__c,FC_Unit_Price__c,ERPProductNr__c,Opportunity__c, Product2__c from ForecastSchedule__c order by CreatedDate asc LIMIT 1 ];
        if(FSList.size()>0){
        fs.isPrimary__c=True;
        }
        Update fs;
    }

}

Please help
can we display data while selected record select from one page to other page by using wrapper class
Hi All, I want a trigger to move quote status from ready to price to proposed when a quote option is created. Here Quote is the Parent Object and Quote Option is the child. So, when ever a quote option is created, I want to move my quote status to proposed. Please hlep.
Please also need test class for the trigger.
Hi, We are trying to acheive pagination using a custom controller and we are unable to complete the same. For instance we are trying to show the next hyperlink on the first page and then the second page should show both next & previous links if there is a third page and the last page should just show the previous link. Can we acheive this using VF page and apex code. If then how do we do it? Your help would be appreciated.
  • November 08, 2010
  • Like
  • 0