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

  • Chatter
    Feed
  • 5
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 3
    Questions
  • 51
    Replies
trigger AccountPhoneUpdate on Account (before Update) 
{
    Map<Id, Account>mapaccount = new Map<Id, Account>([Select Name, Phone From Account Where Id In : trigger.old]);
    
    List<Account>updatedaccount = new List<Account>();
    for(Account a : trigger.new)
    {
        Account oldphone =  mapaccount.get(a.Id);
        if(a.Phone != oldphone.Phone && a.phone !=Null)
        {
            updatedaccount.add(a);
        }
        
    }
    update updatedaccount;
        
    
}
I have a requirement where CustomerSuccess__c field on opportunity to be updated  'true' if CustomerSuccess__c field on Account is 'true' in before Insert event.

I have tried below solution, trigger saved succesfully but it didn't work.
Can anyone explain why my trigger is not working
trigger OppoCustomerSuccessCheckboxUpdate on Opportunity (before insert) 
{
for(Opportunity opp : Trigger.New)
{
	if(Opp.AccountID != null)
	{
		if(Opp.Account.CustomerSuccess__c)
		{
			Opp.CustomerSuccess__c = true;
		}
	}
}
}
Regards,
Akash
 
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);      
   }  */
  
  }

}

 
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
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.