• HARSHIL U PARIKH
  • PRO
  • 2660 Points
  • Member since 2016


  • Chatter
    Feed
  • 75
    Best Answers
  • 2
    Likes Received
  • 25
    Likes Given
  • 46
    Questions
  • 641
    Replies
Hello - I'm trying to pass trigger.new and trigger.old to a single list which then will be passed to a class.

Here's the class I'm calling in the trigger: 
LeadOwnerAssignment.assignOwner(Trigger.new, Trigger.old);
Here is the class method I'm passing the lists to:
public static void assignOwner(List<Lead> newLead, List<Lead> oldLead) {

I'm hoping to do something like this (except pass both trigger.new and trigger.old).
List<Lead> newLeadList = new List<Lead>();
                    for(Lead newLead : Trigger.new){
                        if(newLead.Lead_Id__c == null){
                            newLeadList .add(newLead);
                        }  
                    }
                   LeadOwnerAssignment.assignOwner(newLeadList );
 
Any help would be greatly appreciated. 
Hi,

I am trying to create a trigger which will be checking a checkbox automatically when another process is done.
In specific, I have a custom object Vacation Requests which follows an approval process. If the request is approved, a checkbox "Approved" is being checked.
Then I am creating a trigger which needs to check if the current date is = to the start date of the vacation. if yes, then the checkbox should be selected.
However this doesn't happen.
Any ideas?
trigger Vacation on Vacation_Requests__c (before insert) {
    User u = new User();
    for (Vacation_Requests__c vr:Trigger.new) {
        if (vr.Approved__c==true && vr.Start_Date__c==System.Today()) 
            u.On_Vacation__c=true;        
    }

}

 
How can task assignee get an email notification when there is an attachment added to the task?
I'm writing unit tests that should be relatively simple, but I'm stumbling over some sort of restriction that I'm unfamiliar with due to my inexperience with Apex.  I'm attempting to retrieve usable Contacts from the org to use for testing purposes because I need them to have fully initialized IDs.  I'm unable to use test data because inserting them in tests is problematic due to Contact related triggers.

I'm using the following code snippet in my test method and getting exceptions:
Contact testContact = [SELECT Id, FirstName, LastName from Contact LIMIT 1];
Error: System.QueryException: List has no rows for assignment to SObject

I'm annotating my test method as follows, with no luck:
@isTest(SeeAllData=true)
I'm wondering what I'm missing here.  Any ideas how to get a handle on real Contact records for testing purposes?
Hello,
I am getting an error Compile Error: Invalid type: Opp_Top_X_Designation__c on the first two lines.

The field Opp_Top_X_Designation__c is a lookup to Opportunity from another object Top_X_Designation. Now either the setup is not correct of the format of the code line is not right. Please provide inputs.

list<Opp_Top_X_Designation__c> oppidlist = new list<Opp_Top_X_Designation__c>();
 list<Opp_Top_Designation__c> updatelist = new list<Opp_Top_Designation__c>();
 
 for(Top_Designation__c tx : trigger.new){
 if(trigger.isUpdate || trigger.isInsert){
  if(tx.Document_Attached__c == true && tx.Typeof__c == 'Contract'){
 
 // mt.put(tx.Opp_Top_X_Designation__c, tx.Id);
 // s.add(tx.Opp_Top_X_Designation__c);
Hi - I am very new to dev ( like 1 week :) )... i need to try and write a trigger calculating the unique number of campaign member companies attached to a campaign. For example a campaign can have 50 members representing 10 companies. I need that 10. Would anyone have a similar trigger they can share which I will try and edit ? many many thanks 
Can you give me the examples of Future method and  Asynchronous apex ?

Thanks in Advance
Using this Apex Trigger, how can I add or show the primary contact in the Account object.  I know it can be shown using the contact related list but I would like it to show on the detail page instead as a lookup so users can just click on the contact link instead of looking for the primary contact in the related list.

Here's the code 
trigger PrimaryContact on Contact (before insert, before update) {
  
   set<id> getid = new set<id>();
    string contactId;
    List<Contact> conList = new List<Contact>();
  
    // Trigger Functionality
    if(Trigger.isInsert || Trigger.isUpdate) {
      
        for(Contact cont: Trigger.New) {
          
            if(cont.Primary_Contact__c == true) {
              
                getid.add(cont.AccountId);
                contactId = cont.id;
            }
        }
    }
  
    // Fetching the other Contact which has primary contact checked
    List<contact> cList = [select id, Primary_Contact__c from contact where accountid IN: getid AND Primary_Contact__c = true];
  
    // Unchecking the already checked primary contact
    if(cList.size() > 0) {
      
        for(Contact newClst: cList) {
          
            if(newClst.id != contactId) {
              
                newClst.Primary_Contact__c = false;
                conList .add(newClst);
            }
        }
    } 
    update conList; 
  }
Thanks in advance
 
Hi,

I'm novice to coding and explicitely REST. Is there a way to delete a list of records using REST API. I see bulk insert and update is possible. But there is no proper info on bulk delete. Any help would be appreciated.

Thanks in Advance!
I have never created a Trigger before but I believe when I'm trying to achieve is (relatively!) simple?!  I would like new Child Account Record Owners to have the same owner as the Parent Account Record Owner when the Child is created.  Is this possible?
I have this trigger:

trigger deleteContactReceiver on Contact (before delete) 
{
    List<Contact> con=Trigger.new;
    GDPRContact.deleteContactURN(con); 
}

Invokes:

public static void deleteContactURN(List<Contact> con)
    { 
    for(Contact c:con)
        {
            try
                {
                List<TWAM_URN__c> preURN=[select URN__c, TWAM_SFID__c, TWAM_Last_Name__c, TWAM_URN_Allocation_Time__c, TWAM_URN_Is_Assigned__c from TWAM_URN__c where TWAM_SFID__c=:c.TWAM_SFID__c];
                preURN.get(0).TWAM_SFID__c='';
                System.debug('**** URN IS="+preURN.get(0).TWAM_SFID__c+" ****: ');
                preURN.get(0).TWAM_Last_Name__c='';
                preURN.get(0).TWAM_URN_Allocation_Time__c=null;
                preURN.get(0).TWAM_URN_Is_Assigned__c=FALSE;
                update preURN;
                }    
            catch(Exception e) 
                {
                System.debug('**** An unexpected error has occurred ****: ' + e.getMessage());
                }
           }  // end for 
                
    }  

The testMethod I'm trying to execute is:

public static testMethod void deleteContact()
        {
        Test.startTest();
        Contact con1=new Contact();
        con1=[select Id, AccountId from Contact where Id='0031o00001TWS6RAAX'];
        delete con1;
        List<TWAM_URN__c> postURN2=[select TWAM_SFID__c,TWAM_URN_Is_Assigned__c from TWAM_URN__c where TWAM_SFID__c=:con1.Id LIMIT 1];
        System.assertEquals(FALSE, postURN2.get(0).TWAM_URN_Is_Assigned__c);
        System.assertEquals(null, postURN2.get(0).TWAM_SFID__c);
            
        Test.stopTest();
        }

The line throwing the error is highlighted in bold. A single row in the DB does exist, verified by looking at debug logs.  I know I should not deploy like this as I may have a list of contacts, just trying to get some code working.  

Can you help?  I have spent most of the day trying to solve this one. 

Best wishes,

Roger.
Hi, I'm trying to create a simple program that tracks some demo cases that we have out in the field.  Hitting a wall in regards to every tool I try and use in Salesforce.  

Here is what I'm trying to do, 
I've got a demo kit that needs to transfer ownership from one user to another, but needs to be vetted by their manager.  The manager just needs to be notified that User A is trying to transfer ownership of a case to User B.  Don't want to just let User A or User B change the ownership of this file without having the process vetted by the manager every time. 

Should I use an Approval Process, a Flow, Process Builder, Workflow Rules?  Any help appreciated!
I am trying to auto populate the value of CustomerName field in case screen as "Anonymous" based on recordtype selection. Can somebody help me on this? 

I tried using workflow but  i am not getting the CustomerName field in case object and i could find that the CustomerName field is related to account object, due to which i am unable to use workflow to auto populate the value of CustomerName field in case screen.
Hi Everyone !

I want to make a validation rule on the object "Opportunity", the rule is basically :

We want to check the Stage of the opportunity , if the opp is in stage = Negotiation / Verbal / Contract / Launched / Invoiced / Closed , and the field "agent" (Sales_Agent__c) is different from "None (Sales Agent)" and the field "Agent_Commission__c" is blank and the field "Agent_Commission_Amount_Manual__c" is blank.

So if all this is gathered, an error message is displayed:"Please check the agent commissions. ..."

So in order to do that , i have created a validation rule , like this:

AND(
OR(
text(StageName) = "Negotiation",
text(StageName) = "Verbal",
text(StageName) = "Contract",
text(StageName) = "Launched",
text(StageName) = "Invoiced",
text(StageName) = "Closed",
OR(
ISBLANK( Agent_Commission__c )
,
Sales_Agent__c<>"None (Sales Agent)"
,
ISBLANK(Agent_Commission_Amount_Manual__c)))

But i have an issue , when we apply the validation rule , even if the field "Agent" is equal to "None (Sales Agent)" the rule still applies.

Thanks for your help !
Hi there,

Another workflow rule question! I'm looking to set up an e-mail alert when the following criteria are met:
  • When an Account name is changed (not created, only when changed)
  • Account Type = "Customer" or "In delivery"
I'm banging my head against the "you cannot use this operator with a picklist" wall. Help me! The closest I could get is this:
 
AND(
OR(
NOT(ISBLANK(PRIORVALUE( Name ))),ISCHANGED( Name )),
NOT(ISNEW()),
ISPICKVAL (Type  = 'In delivery'),
ISPICKVAL (Type = 'Customer')
)

Thanks,
Dan​
I have related list under account object for suppose an account record has 5 related recored on a object, can  i get thosed related list in account field?


User-added image
As shown in the above image, this is a related list on Account object, so i need a field on account object and show all the related list names in the field 

for example : 

Account_field1__c =  Contarct name 1 , contract name 2 , contract name 3 ........ contract name 6 .
Account_field1__c =  619754.1STD ,619744STD,619733STD,619730STD,617208.6STD.



is this possible ?
  • August 15, 2017
  • Like
  • 0
Can you create a workflow rule that updates a field in a different object?

We are receiving spam Leads on our org but we have been applying some techniques in order to stop them but no luck with it.

We can filter on the leads spam those spam leads (applying filter as we know how to distinguish them from real ones) but we can not stop them to receive the email when a new lead comes.

Place where Leads comes to our org:
- We have a web-to-Lead form (only one) on our website but we have reCaptcha and we are sending extra data when the user have submitted this form so we are sure we are not getting this fake leads from there.

Configuration:

Lead Settings/Notify Default Lead Owner is enabled

- We have set a customize template when a leads comes, assigned to a lead assignment rule.

When a lead comes, we are getting (default owner) a different template. This is the template we get (it seems a general one from Salesforce):

A lead has been assigned to you, the default owner. Click the link below to view the record in salesforce.com
https://domain-org.salesforce.com/this-is-example-of-id-org

We have seen that this templates is not set anywhere. So we are receiving spam and it seems that the lead assignment rule we have set to block this spam is not working.

 

Is there a way when a lead comes to our organization, before of adding to the leads list, evaluate it on Salesforce (for any field: lead status, lead source, email, ...) ?

Thanks in advance

 

Hello Developers!

I have one of object which has thousands of records with all of them having a Zip Codes (Mostly US). Now, how do I create a formulas to populate Country, City, State, and County.

I have found one excel file online which has all of the US states, Zip, county, City infomation.

I know this is goes somewhere around creating a Custom Setting in salesforce and import all the data from excel file but I am wondering how to go about it?

Should I create a LIST setting type or Hierarchy setting type? Which one suits best in my case?

Thank you for your help!
Hello Developers!

I am trying to count number of product sold by won opportunities but I am getting error in line 21 query as:


Id, Opportunity_Stage__c FROM OpportunityLineItems WHERE Opportunity_Stage__c
                              ^
ERROR at Row:2:Column:69
Didn't understand relationship 'OpportunityLineItems' 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.

Trigger Code:
Trigger CountingNUmberOfProductSold on OpportunityLineItem (After Insert, After Update, After Delete, After UnDelete) {
	List<Id> ProductIds = New List<Id>();
    If(Trigger.IsInsert || Trigger.IsUpdate || Trigger.IsUnDelete){
        For(OpportunityLineItem OppLineItem : Trigger.New){
            If(OppLineItem.Product2Id != null && OppLineItem.Opportunity_Stage__c == 'Closed Won'){
                 ProductIds.add(OppLineItem.Product2Id);
            }
        }      
    }
    If(Trigger.IsDelete){
        For(OpportunityLineItem OppLineItem : Trigger.Old){
            If(OppLineItem.Product2Id != null && OppLineItem.Opportunity_Stage__c == 'Closed Won'){
                ProductIds.add(OpplineItem.Product2Id);
            }
        }
    }
    
    List<Product2> finalProduct2ListToUpdate = New List<Product2>();
    
    For(Product2 Product : [Select Id, Number_Of_Quantity_Sold__c,
                            		(Select Id, Opportunity_Stage__c FROM OpportunityLineItems WHERE Opportunity_Stage__c = 'Closed Won')
                            			FROM Product2 WHERE Id =:ProductIds])
    {
    	Product.Number_Of_Quantity_Sold__c = Product.OpportunityLineItems.size();
        finalProduct2ListToUpdate.add(Product);
    }
    
    try{
        If(!finalProduct2ListToUpdate.IsEmpty()){
            update finalProduct2ListToUpdate;
        }
    }
    catch(Exception e){
        system.debug('Thown Exception Name For CountingNUmberOfProductSold Trigger Is - ' + e.getTypeName() + ' ' + 'And Message Is - ' + e.getMessage());
    }   
}

 
Hello Developers!

I have this trigger on opportunity which allows only $500 opportunity amount per day per user. Now Trigger seem to be working fine. But however, I have a question.
Since the upcoming record's Id is not availble in Trigger.New then why is it works at line 18? Wouldn't the opp.Id is null at that line?
Trigger FiveHundred_Dollars_Opp_Amount_Limit on Opportunity(Before Insert, Before Update, After UnDelete){
     
     If(Trigger.IsInsert || Trigger.IsUpdate || Trigger.IsUnDelete){
         
         For(Opportunity opp : Trigger.New){
             
             If(Opp.Amount > 500){
                 Opp.addError('Opportunitys Amount Can not be greater than $500 per day.');
             }
             else If(Opp.Amount == null){
                 // Let it go.
             }
             
             else If(opp.Amount != null){
                 
                 List<Opportunity> FetchingCurrentUsersTodaysOpps = [Select Id, Amount
                                                                             FROM Opportunity
                                                                                 WHERE Id != :Opp.Id
                                                                                 AND   CreatedDate = Today
                                                                                 AND   Amount != null
                                                                                 AND   OwnerId =:Opp.OwnerId];
                 Double SummingAmount = Opp.Amount;
                 If(!FetchingCurrentUsersTodaysOpps.IsEmpty()){
                     
                     For(Opportunity EveryOpp : FetchingCurrentUsersTodaysOpps){
                         SummingAmount += EveryOpp.Amount;
                     }
                 If(SummingAmount > 500){
                     Opp.addError('You have reached the miximum limit of $500 opportunity Amount Per Day.');
                 }
                 }
             }
         }
     }
}

Thank You!
Apex Class:
public class RecursionBlocker{
   public static Boolean flag = true;
}
Trigger: I am creating an event record once the record is approved.
Trigger CreatingAnEvent on Approval_Requests__c(After update){
 
     If(RecursionBlocker.Flag = true){

     RecursionBlocker.Flag = false;
     
      Event evt = New Event();
      If(Trigger.isUpdate)
      {
            For(Approval_Requests__c AR: Trigger.New)
            {
                                           
                   If(AR.Approval_Status__c == 'Approved') // Then Create an event record.
                   { 
                       evt.StartDateTime = AR.Start_Date_Time__c;
                       evt.ACA_Location__c = AR.ACA_Location__C;
                       evt.Type = AR.Type__C;
                       evt.Description = AR.Situation__C;
                       evt.Subject = AR.Subject__C;
                       evt.OwnerID =  String.valueOf(AR.OwnerId);  // "Owner" is an assign to
                       evt.Whatid = AR.id;                        // "what" is a relate to
                       evt.DurationInMinutes =   0; 
                       evt.Automatically_Created_Event__c = TRUE;
                       evt.Approved__C = TRUE;
                       evt.Other_Location__C = AR.Other_Location__C;
                       evt.Organization__C = AR.Account__C;
                       evt.whoid = AR.Contact__c;                 // Who is Name field label on an Event and it's looking up to 
                                                                  //     either Lead or Contact. For our purpose of creation, we are looking up 
                                                                  //       to Contact. Id to Id match. 
                     insert Evt;
                                              
                   }
                   else{
                       // Do Nothing
                   }
                   
            }   
   
        }
    }
}
Now, once the record gets approved then an event record gets created -- which is fine!
But when I update the record again, then new event is created which is needed to be stop.
Thak You for the help!


 
Hello Developers!

I have a trigger on contact which rollsup number of contact on account.
Trigger works fine but however I have a question.
Trigger Code:
Trigger ContacstTotalCount On Contact(After Insert, After Update, After Delete, After Undelete){
    
    Set<ID> AccountIds = New Set<ID>();
    
    If(Trigger.IsInsert || Trigger.IsUpdate || Trigger.IsUndelete){
        For(Contact C:Trigger.New){
            AccountIds.add(C.AccountID);
        }
    }
    If(Trigger.IsDelete){
        For(Contact C:Trigger.Old){
            AccountIds.add(C.AccountID);
        }
    }
    
    List<Account> AccountListToUpdate = New List<Account>();
    
    For(Account a: [Select Id, total_contacts__c, (Select Id FROM Contacts) FROM Account WHERE ID = :AccountIds]){
        
        a.total_contacts__c = a.contacts.size();
        AccountListToUpdate.add(a);
    }
    try{
    Update AccountListToUpdate;
    }
    Catch(Exception E){
    System.Debug('Thrown Exception is: ' + E.getMessage());
    }
    
}

In line 18 I am having SOQL in parameters of FOR loop. Would that be okay or I should be write something like following?
List<Account> FetchingActs = [Select Id, total_contacts__c, (Select Id FROM Contacts) FROM Account WHERE ID = :AccountIds];
    
    For(Account a: FetchingActs ){
        
        a.total_contacts__c = a.contacts.size();
        AccountListToUpdate.add(a);
    }
I mean... if I take the above approach then wouldn't it only work for first 50,000 Accounts?
And also what happens when each account has 5 contacts then would query fetch 50,000 accounts plus 5 contact from each?
Thank You!
 
Hello Developes!

I have a trigger which counts number of unique email address contacts on Account.
Trigger Code:
Trigger UniqueEmailCons on Contact(After Insert, After Update, After Delete, After Undelete){
    
    List<ID> accountIds = New List<ID>();
    
    If(Trigger.IsInsert || Trigger.IsUpdate || Trigger.IsUndelete){
        For(Contact con : Trigger.New){
            accountIds.add(con.AccountID);
        }
    }
    If(Trigger.IsDelete){
        For(Contact con : Trigger.old){
            accountIds.add(con.AccountID);
        }
    }
    
    Set<String> UniqueEmails = New Set<String>();
    List<Account> AccountListToUpdate = New List<Account>();
    
    For(Account act : [Select ID, Unique_Email_Contacts__c, (Select Id, Email FROM Contacts) FROM Account WHERE Id = :accountIds])
    {
        
        act.Unique_Email_Contacts__c = 0;
        
        For(Contact c : act.contacts)
        {
            If(C.Email != null)
            {
                UniqueEmails.add(C.Email);
            }
        }
        act.Unique_Email_Contacts__c = UniqueEmails.size();
        AccountListToUpdate.add(act);
        
    }
    try{
        update AccountListToUpdate;
    }
    Catch(Exception e){
        System.debug('Exception thrown is::: ' + e.getMessage());
    }
}
Trigger works fine for individual getting inserted, updated, deleted record etc.. but when I update all the contacts togather then all the accounts in org (let's say 18 ) of them gets updated as follow:

Account - 1 gets updated with values of Unique_Email_Contacts__c as 1
Account - 2 gets updated with values of Unique_Email_Contacts__c as 2
Account - 3 gets updated with values of Unique_Email_Contacts__c as 3 etc...


Thank you for the help!

 
Hello Developers!
I am trying to write trigger on opportunity which would sum the Amount field on Account.
This might be possiable via standard but I am trying to have similar trigger on different set of object and solving this would solve the other one as well.
Trigger:
trigger AmountRollup on Opportunity(After insert, After update, After delete, After undelete){
    
    Set<ID> accountIds = New Set<ID>();
    
    If(Trigger.IsInsert || Trigger.IsUpdate || Trigger.IsUndelete){
        For(Opportunity opp: Trigger.New){
            accountIds.add(opp.AccountID);
        }
    }
    If(Trigger.IsDelete){
        For(Opportunity opp: Trigger.Old){
            accountIds.add(opp.AccountID);
        }
    }
    
    List<Account> AccountListToUpdate = New List<Account>();
    Double AmountTotal = 0.00;
    
    
    For(Account a : [Select id, total_opportunity_amount__c, 
                                (Select id, Amount FROM opportunities) 
                                FROM Account WHERE ID = :accountIds])
    {
         For(Integer I = 0; I < a.opportunities.size(); I++)
         {
             AmountTotal += a.opportunities.Amount; // Here I am trying add all amount sum into AmountTotal
             a.total_opportunity_amount__c = AmountTotal;
             AccountListToUpdate.add(a);
         }
                                
    }
    try{
    update AccountListToUpdate;
    }
    catch(Exception E){
        system.debug('Error thrown is: ' + E.getMessage());
    }
}

Thank you for the help!
Hello Developers!

I have a trigger on contct which counts number of contact record as rollup on account
Trouble: is that when I insert new contact then total_contacts__c on account becomes 0 then when I enter second contact it becomes 1 and so on..
At the end of the day if I have 5 contacts then it will show up as 4.
trigger:
Trigger ContacstTotalCount On Contact(Before Insert, Before Update, After Delete, After Undelete){
    
    Set<ID> AccountIds = New Set<ID>();
    
    If(Trigger.IsInsert || Trigger.IsUpdate || Trigger.IsUndelete){
        For(Contact C:Trigger.New){
            AccountIds.add(C.AccountID);
        }
    }
    If(Trigger.IsDelete){
        For(Contact C:Trigger.Old){
            AccountIds.add(C.AccountID);
        }
    }
    
    List<Account> AccountListToUpdate = New List<Account>();
    
    For(Account a: [Select Id, total_contacts__c, (Select Id FROM Contacts) FROM Account WHERE ID IN :AccountIds]){
        
        a.total_contacts__c = a.contacts.size();
        AccountListToUpdate.add(a);
    }
    try{
    Update AccountListToUpdate;
    }
    Catch(Exception E){
    System.Debug('Thrown Exception is: ' + E.getMessage());
    }
    
}

Thank you for the help!
Hello Developers

I am writing trigger in which it stops user to create a lead record if he/she enters more than 100 records per day.

trigger: currently i am doing it on two records since it's easy to test.:)  but however, trigger is not getting fired and it allows me to create more than 2 opportunities per day.
 
Trigger NoMoreThan100LeadsPerDayPerUser On Lead(Before Insert){
    // We need to write a trigger so there should be no more then 100 leads per day per user.
    // In other words one user can only create no more than 100 leads per day.
    Id userId;
    
    If(Trigger.IsInsert){
        For(Lead Ld: Trigger.New)
        {
            userId = Ld.OwnerID;
            List<Lead> TodaysLead = [Select ID FROM Lead 
                                        WHERE CreatedDate = :Date.Today() AND OwnerID = :UserId LIMIT 3];
            
            If(TodaysLead.size() > 2)
            {
                Ld.addError('You have rich the limit for creating a leads for today.');
            }
        }
    }
}

Thank you for the help!

Hello Developers!

I am trying to write a trigger on opportunity where it would throw an error when user exceeds 10,000 daily limit of opportunity amount. One sales rep can create number of opportunities up to the amount where Amount can not exceed 10,000 per day.

Here is my logic: When there is a new record inserted in system, I am getting that record's userId, and createdDate in variables. Then I have a SOQL which fetches the all opportunities in database which is created by that user and on the today's  date (I am not too sure my SOQL in the code below). Once the records are fetched, I have a loop which sumes up the amount from the fetched opportunities in SOQL and if that sum is greater then 10,000, I am throwing an error.
 

Trigger TenThousandDollarsLimit on Opportunity(Before Insert){
    // We need to write a trigger so one user can not create more then
    // $10,000 of opportunity per day.
    
    User OppOwner;
    ID OppOwnerID;
    Double AmountSum;
    Date TodaysDate;
    
    For(Opportunity opp: Trigger.New){
        
        OppOwner = opp.Owner;
        OppOwnerID = opp.OwnerId;
        TodaysDate = opp.createdDate.date();
        
        
        List<Opportunity> opps;
        opps = [Select Id, Amount FROM Opportunity WHERE OwnerId = :OppOwnerId AND CreatedDate = :TodaysDate];
        
        
        For(Integer I = 0; I < opps.size(); I++)
        {
            AmountSum = opps[I].Amount;
        }
        
        If (AmountSum > 10000){
            opp.addError('You have exceed your daily limit of $10,000');
        }
        else{
            // do nothing
        }
    }
    
}
Here is an Error Message while saving the first record:
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger TenThousandDollarsLimit caused an unexpected exception, contact your administrator: TenThousandDollarsLimit: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.TenThousandDollarsLimit: line 14, column 1


Thank you for the help guys!
Hello Developers!

I have a situation here in which trigger is not firing.
Master object: Volunteer_Project__c and Detail object: Participation__c
I want to count number of unique email addresses (Total_Associated_Volunteers__c) of Participation__c on Volunteer_Project__c.

Approach: Whenever there is a record entry in child for one particular master, I am compering that newly inserting record's email address to all of the child records of that master. If similar email found then Unique_Roll_Up__c on that detail record is 0 otherwise 1. At the end, I am putting rollup summary on Unique_Roll_Up__c at the Master object.

Trigger:
 
Trigger UniqueRollUp On Participation__c(Before Insert, Before Update){

    List<Participation__c> Partici = New List<Participation__c>();
    Set<String> UniqueEmailSet = New Set<String>();
    Set<ID> ProjIds = New Set<ID>();
    
    If(Trigger.IsInsert || Trigger.IsUpdate)
    {
        For(Participation__c P: Trigger.New)
        {    
            ProjIds.add(P.Volunteer_Project_Name__c);    
        }
    }
    
    Partici = [Select Volunteer_Email__c FROM Participation__c WHERE Volunteer_Project_Name__c = :ProjIds];
    
    For(Participation__c Pa: Trigger.New){
        If(Pa.Volunteer_Email__c != null){
            
            for(Integer I = 0; I<Partici.size(); I++){
                if(Pa.Volunteer_Email__c == Partici[0].Volunteer_Email__c){
                    Pa.Unique_Roll_Up__c = 0;
                }
            }
        }
        else{
            Pa.Unique_Roll_Up__c = 1;
        }
    }
}

Thank You!
Hello Developers,

I am running into this following situation:

I have a trigger on Cases which updates Total_Cases_Count__c on Account and Contacts. It works fine for insert, update, and all delete and undelete conditions such as when I insert case with account named "Appolo" and Contact named "Mark" then both "Appolo" and "Mark" will have Total_Cases__c as 1. But however, when I just take the contact "Mark" off from that case then under the Mark's contact record Total_Cases__c is still 1 even though mark doersn't have any cases under the related list anymore.
Thank you for your help!

Code:
Trigger CaseRecordCount on Case(After Insert, After Update, After Delete, After UnDelete){
    
    List<ID> AccountIds = New List<ID>();
    List<ID> ContactIds = New List<ID>();
    
    If(Trigger.IsInsert || Trigger.IsUpdate || Trigger.IsUnDelete){
        For(Case c: Trigger.New){
            AccountIds.add(c.AccountId);
            ContactIds.add(c.ContactId);
        }
     }
    If(Trigger.IsDelete){
        For(Case c: Trigger.Old){
            AccountIds.add(c.AccountId);
            ContactIds.add(c.ContactId);
        }
     }
     
     List<Account> AccountListToUPdate = New List<Account>();
     List<Contact> ContactListToUpdate = New List<Contact>();
     
     For(Account act: [Select Total_Cases__c, (Select ID FROM Cases) FROM Account WHERE ID = :AccountIds]){
     act.Total_Cases__c = act.Cases.size();
     AccountListToUpdate.add(act);
     }
     
     For(Contact con: [Select Total_Cases__c, (Select ID FROM Cases) FROM Contact WHERE ID = :ContactIds]){
     con.Total_Cases__c = con.Cases.size();
     ContactListToUpdate.add(con);
     }
     
     try{
         Update AccountListToUpdate;
         Update ContactListToUpdate;
     }
     Catch(Exception E){
         System.Debug('Error Message: ' + e.getMessage());
     }
    

}

 
Hello Developers,

I have a trigger on object called Approval__C which creats an event record when Approval_Status__C is Approved.

Trigger is not automatically getting fired when approver approves the record but when I update the 'Approved' record manually then trigger gets fired. How do I make this trigger fire automatically when Approval_Status__c is Approved.
Trigger:
Trigger CreatingAnEvent on Approval__c(After update){
    
      Event evt = new Event();
    
      If(Trigger.isUpdate || Trigger.isUndelete)
      {
            For(Approval__c AP: Trigger.old)
            {
               if(AP.Approval_Status__c != 'Approved')
               {
                   // Nothing    
               }                            
               else
               {
                   evt.ACA_Location__C = AP.Location__c;
                   evt.StartDateTime = AP.Start_Time__c;
                   evt.EndDateTime = AP.End_Time__c;
                   evt.Type = AP.Type__c;
                   evt.Description = AP.Situation__C;
                   evt.Subject = AP.Subject__C;
                   evt.OwnerID =  String.valueOf(AP.OwnerId);                              // "Owner" is an assign to
                  // evt.What = AP.RecordID;                                                // "what" is a relate to 
                  evt.DurationInMinutes =   0; 
                 insert evt;                          
               }
               
            }    
    }
}
Thank you for the help!


 
Hello Developer Community!

I am trying to create a event record based on approval process updated a field called "Approval Status" to Approved.
But Event record is not getting created for some reason..
Here are some images for it..
User-added image

Process Builder COnfiguration:
User-added image

User-added image

User-added image

Appreciated!
Hello Developers!
I have a rollup summary sum trigger on child object and it works fine accept it doesn't allow me to delete the child record once created.
I appreciate your help!
Trigger DirectCareAmount on Direct_Care_Assistance__c( after insert, after update,after delete,after undelete) {
     Set<Id> DispoIdSet= new Set<Id>();
     List<Cat_Disposition__C > DispoListToUpdate = new List<Cat_Disposition__C>();
     Map<Id,Cat_Disposition__c>  MapDispoToReset  = new Map<Id,Cat_Disposition__c>();
     
    if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete)
    {
        for(Direct_Care_Assistance__c DC: Trigger.new)
        {
            if(DC.Cat_Disposition__C != null)
                {
                    DispoIdSet.add(DC.Cat_Disposition__C );
                }     
        }
    }
   If(Trigger.isDelete) 
      { 
       for(Direct_Care_Assistance__c DC: Trigger.old) 
           { 
               if(DC.Cat_Disposition__C != null) 
                   {     
                           DispoIdSet.add(DC.Cat_Disposition__C );
                           MapDispoToReset.put( DC.Cat_Disposition__C, new Cat_Disposition__C ( Id= DC.Cat_Disposition__C,
                                                                                           Money_Spent_on_Direct_Care_Assistance__c = 0 ) );
                   } 
           } 
       }
    
   for(AggregateResult res : [SELECT Count(id)Quantity, Cat_Disposition__C ,sum(Dollar_Amount__c)addition FROM Direct_Care_Assistance__c WHERE                                                                     
                                                                                   Cat_Disposition__C IN :DispoIdSet group by Cat_Disposition__C ]) 
        {
                DispoListToUpdate.add(new Cat_Disposition__C         (     Id=(Id)res.get('Cat_Disposition__C'), 
                                                                           Money_Spent_on_Direct_Care_Assistance__c =  (Double)res.get('addition')
                                                                     )     
                                     );
                                                        
               if(Trigger.IsDelete && MapDispoToReset.containsKey(  (Id)res.get('Cat_Disposition__C ') )  )
                    {
                            MapDispoToReset.remove(  (Id)res.get('Cat_Disposition__C')  );                  
                    }
            }
        for ( ID cid : MapDispoToReset.keySet() )
        {
          DispoListToUpdate.add((Cat_Disposition__C)MapDispoToReset.get(cid));
        }
        
    try
    {
      update DispoListToUpdate;
    }
    catch(DmlException de)
    {
      System.debug(de);
    }
}
Error:  when delete the child record:

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 DirectCareAmount caused an unexpected exception, contact your administrator: DirectCareAmount: execution of AfterDelete caused by: System.SObjectException: Invalid field Cat_Disposition__C for AggregateResult: Trigger.DirectCareAmount: line 37, column 1". 


 
Hello Developers!
I was wondering if I can use your help on following trigger.
Trigger works FINE for all conditions accept when the last record is deleted.
About Trigger:
Two Object with Parent-Child lookup relationship.
Object-1 = Contact as Parent
Object-2 = Merchandise__C as Child.

Count "Transaction_Count__C" on Contact means just counting number of Merchandise__c records for Contact.
Count "Total_Money_Spent_for_ACA_Products__c " on Contact means count sum of all Transaction_Total__c from Merchandise__c.

How Merchandise__C look up to contact? - By Individual_Customer__c field.

Trigger:
Trigger TotalTransCostCount on Merchandise__C( after insert, after update,after delete,after undelete) {
     Set<Id> ConIdSet = new Set<Id>();
     List<Contact> ConListToUpdate = new List<Contact>();
     
    if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete)
    {
        for(Merchandise__C Merch: Trigger.new)
        {
            if(Merch.Individual_Customer__C != null)
                {
                    ConIdSet.add(Merch.Individual_Customer__C);
                }     
        }
    }
    If(Trigger.isDelete)
    {
       for(Merchandise__C Merch: Trigger.old)
       {
            if(Merch.Individual_Customer__C != null)
            {
                ConIdSet.add(Merch.Individual_Customer__C );    
            } 
        }
    }
   for(AggregateResult res : [SELECT Count(id)Quantity, Individual_Customer__C ,sum(Transaction_Total__c)addition FROM Merchandise__C WHERE 
                                                                       Individual_Customer__C IN :ConIdSet group by Individual_Customer__C ]) 
        {
                ConListToUpdate.add(new Contact         (     Id=(Id)res.get('Individual_Customer__C'), 
                                                              Total_Money_Spent_for_ACA_Products__c =  (Double)res.get('addition'),
                                                              Transaction_Count__C =  (Integer)res.get('Quantity')     )     
                                   );
        }
    try
    {
      update ConListToUpdate;
    }
    catch(DmlException de)
    {
      System.debug(de);
    }
}
Problem:
If I create 3 merchandise__c records with all have Transaction_Total__c = 10 for contact named John Doe then Total_Money_Spent_for_ACA_Products__c becomes 30 for him.
Now if I delete one record then it becomes 20.
Then delete another record it comes 10.
Now, If I delete his last record then it still stays to 10.??
Thank You!
 
Hello Developers,

I am trying to take a size for this variable "res" from this SOQL query---> AggregateResult res : [SELECT Custom_field__C];
I am using Count__C = res.size() it throws an error as
Method does not exist or incorrect signature: [AggregateResult].size()
I know I can use .size() on list but I am not sure about on this "res."
Thank you for the help!
Hello Developers!

I need your help in following.
I have two objects with lookup relationship 1) Projects__c Parent and 2) Participants__c as child
Requirement: Create roll up summary on parent to count all devoted hours from child.
My trigger:
Trigger CountHours On Participants__c (After Insert, After Update, After Delete, After Undelete){
    
    List<Participants__c> Parti = New List<Participants__c>();
    Set<ID> ProjIds = New Set<ID>();
    
    if (!Trigger.isDelete)
    {
        for (Participants__c PC: Trigger.New)
        {
        ProjIds.add(PC.Project__c);
        }
    }
    else 
    { 
       for (Participants__c PC: Trigger.old)
        {
        ProjIds.add(PC.Project__c);
        }
    }
    Parti = [Select Devoted_Hours__c From Participants__c where Project__c IN: ProjIds];
    Double X = 0;
    for(Integer I = 0; I<Parti.size(); I++){
        if(Parti[I].Devoted_Hours__c != null){
            X += Parti[I].Devoted_Hours__C;
        } 
    }
    List<Projects__c> Projs = New List<Projects__c>([Select Total_Devoted_Hours__c From Projects__c Where ID IN: ProjIds]);
   if (!Trigger.isDelete){
            for(Participants__c Partici: Trigger.New){   
                for (Projects__c P: Projs){ 
                     P.Total_Devoted_Hours__c = X;
                }
            }
        }
        else {
            for(Participants__c Partici: Trigger.Old){    
                for (Projects__c P: Projs ){ 
                    P.Total_Devoted_Hours__c = X;
                }
            }
        }
    
    update Projs;
 
}

This trigger works fine for when record is inserted, updated deleted, or even undeleted but strange thing is when I update all child records from list views (using Mass Update App), all parents gets updated with the sum of devoted hours.
How?
Here is a list view of child object:
User-added image
Here is a list view of parent object
User-added image
If I update list view of child with as Mass Update, 
the parent records gets updated like this,
User-added image
 I am wondering why all of the project got updated with total of all Participants__c's devoted hours?
Thank You for the help guys..
Hello Developers!
I need some help on this..
Two Objects with Master-Detail: 1) Volunteer_Project__c (Master) , 2) Participation__c (Detail)
Task: Need to count identical email address on parent for child.
Trigger:
Trigger UniqueEmailCount On Volunteer_Project__c(before insert, before update)
{
    List<Participation__c> ParticipationList = new List<Participation__c>();
    Set<String> uniqueEmails = new Set<String>();
    
    
    ParticipationList = [SELECT Volunteer_Email__c FROM Participation__c where Volunteer_Project_Name__c IN :Trigger.New];

        for (Integer i = 0; i< ParticipationList.size(); i++)
        {uniqueEmails.add(ParticipationList[i].Volunteer_Email__c);
        }
        
        for(Volunteer_Project__c proj: Trigger.new)
        { 
        proj.Total_Associated_Volunteers__c = uniqueEmails.size();
        }
}
Problem:
When I individually add parent and then child for them it counts unique emails. All good as of now!
But when I Mass update all parent then they all gets updated with same value.
(e.g., Let's say 3 projects A, B, C and each has Total_Associated_Volunteers__c as 5, 10, 15.
But When I update all 3 project as Mass Update then all Projects has Total_Associated_Volunteers__c = 15)
Thank you for the support!
 
Hello Developers,
Need your thoughts/help..
I have a trigger on child object which updates check box on contact as True on creation of child. (This happens in below trigger)
But it doesn't allow me to delete the child for that contact anymore.
Trigger CrossObjectContactUpdate on Merchandise__C(after delete, after insert, after update){


    List<Merchandise__c> Merch = New List<Merchandise__C>();
    List<Contact> Con = New List<Contact>();
    Set<ID> ConID = New Set<ID>();
        
    for(Merchandise__c M: Trigger.New)
    {
       ConId.add(M.Individual_Customer__C);
    }
    Boolean T = True;
    
    Contact Con1 = [Select X_CrossObj__c From Contact Where ID IN: ConID];
    for(Merchandise__C MC: Trigger.New)
    {    
        Con1.X_CrossObj__c = T;
    }
    update Con1;
    
}

This trigger is created to just update the record of parent. So my other triggers can fire. So, having checkbox checked or not checked don't really matter. Its all about update.
Thank You!

Well, one more Q) Can we update parent record (just update) when child is created, deleted, updated etc.. with process builder? IF yes, then I can take that path instead of trigger above.
Thank you guys for help!
 
Hello Developers!

I have this trigger on opportunity which allows only $500 opportunity amount per day per user. Now Trigger seem to be working fine. But however, I have a question.
Since the upcoming record's Id is not availble in Trigger.New then why is it works at line 18? Wouldn't the opp.Id is null at that line?
Trigger FiveHundred_Dollars_Opp_Amount_Limit on Opportunity(Before Insert, Before Update, After UnDelete){
     
     If(Trigger.IsInsert || Trigger.IsUpdate || Trigger.IsUnDelete){
         
         For(Opportunity opp : Trigger.New){
             
             If(Opp.Amount > 500){
                 Opp.addError('Opportunitys Amount Can not be greater than $500 per day.');
             }
             else If(Opp.Amount == null){
                 // Let it go.
             }
             
             else If(opp.Amount != null){
                 
                 List<Opportunity> FetchingCurrentUsersTodaysOpps = [Select Id, Amount
                                                                             FROM Opportunity
                                                                                 WHERE Id != :Opp.Id
                                                                                 AND   CreatedDate = Today
                                                                                 AND   Amount != null
                                                                                 AND   OwnerId =:Opp.OwnerId];
                 Double SummingAmount = Opp.Amount;
                 If(!FetchingCurrentUsersTodaysOpps.IsEmpty()){
                     
                     For(Opportunity EveryOpp : FetchingCurrentUsersTodaysOpps){
                         SummingAmount += EveryOpp.Amount;
                     }
                 If(SummingAmount > 500){
                     Opp.addError('You have reached the miximum limit of $500 opportunity Amount Per Day.');
                 }
                 }
             }
         }
     }
}

Thank You!
Hello Developers!

I have a trigger on contct which counts number of contact record as rollup on account
Trouble: is that when I insert new contact then total_contacts__c on account becomes 0 then when I enter second contact it becomes 1 and so on..
At the end of the day if I have 5 contacts then it will show up as 4.
trigger:
Trigger ContacstTotalCount On Contact(Before Insert, Before Update, After Delete, After Undelete){
    
    Set<ID> AccountIds = New Set<ID>();
    
    If(Trigger.IsInsert || Trigger.IsUpdate || Trigger.IsUndelete){
        For(Contact C:Trigger.New){
            AccountIds.add(C.AccountID);
        }
    }
    If(Trigger.IsDelete){
        For(Contact C:Trigger.Old){
            AccountIds.add(C.AccountID);
        }
    }
    
    List<Account> AccountListToUpdate = New List<Account>();
    
    For(Account a: [Select Id, total_contacts__c, (Select Id FROM Contacts) FROM Account WHERE ID IN :AccountIds]){
        
        a.total_contacts__c = a.contacts.size();
        AccountListToUpdate.add(a);
    }
    try{
    Update AccountListToUpdate;
    }
    Catch(Exception E){
    System.Debug('Thrown Exception is: ' + E.getMessage());
    }
    
}

Thank you for the help!
There is custom obj and have a checkbox .
I want to sort the records based on Created date.
The checkbox should be checked for the record if created date is the oldest among the list of records.

 
Hello - I'm trying to pass trigger.new and trigger.old to a single list which then will be passed to a class.

Here's the class I'm calling in the trigger: 
LeadOwnerAssignment.assignOwner(Trigger.new, Trigger.old);
Here is the class method I'm passing the lists to:
public static void assignOwner(List<Lead> newLead, List<Lead> oldLead) {

I'm hoping to do something like this (except pass both trigger.new and trigger.old).
List<Lead> newLeadList = new List<Lead>();
                    for(Lead newLead : Trigger.new){
                        if(newLead.Lead_Id__c == null){
                            newLeadList .add(newLead);
                        }  
                    }
                   LeadOwnerAssignment.assignOwner(newLeadList );
 
Any help would be greatly appreciated. 
Hi All,

I want insert the same attachment of the Opportunity object to the Account object.
When I query to the attachment object and get the body of that file then I'm not able to convert the "Blob" format of that body.

Please give the correct tested solution (snippet code).

Thanks in Advance.
I am using an SOQL in a webservice that is querying the Contact object based on the BirthDate field. The webservice request has the date in the format of 'yyyy-MM-dd',i.e.,1962-01-29 as an example.
I am not able to use this value to query the Contact Object. I tried converting this String Date into Date object. However, it always has 00:00:00 at the end. I tried the below options.
String strDate = '1962-01-29'; 
Date birthDate = Date.valueOf(strDate) ==> This results in 1962-01-29 00:00:00 String strDate = '1962-01-29'; 

Date dob = Date.valueOf(strDate) 
Datetime dt = Datetime.newInstance(dob.Year(),dob.Month(),dob.day()); 
Date birthDate = dt.date() ==> This also results in 1962-01-29 00:00:00

How do I construct a Date object (without time) from the string date '1962-01-29'?
I did search for solutions in various forums and most of them are suggesting the above two solutions only, which does not work. I am not sure whether this behavior was changed in some Salesforce's releases.

I even tried the Date.parse() method. Whatever I do, I always get the Date with 00:00:00 at the end and this is messing up the SOQL query. When the SOQL is executed, I am getting a message saying [Exception: Line 1:343 No Viable Alternative at character '' ]. The SOQL is built as shown below.
 
USER_DEBUG [112]|DEBUG|Query:: SELECT id,LastName,FirstName,BirthDate,MiddleName__c,MailingAddress,OtherAddress,EmploymentStatus__c,Suffix__c,MaritalStatus__c,Gender__c,MailingState__c,HomePhone,MobilePhone,Email FROM Contact WHERE LastName LIKE 'Smith%' AND BirthDate = 1962-01-29 00:00:00  ORDER BY lastName,firstName,BirthDate LIMIT 50

If I run this query in workbench, I get the same error message.

Can someone help?
  • January 05, 2019
  • Like
  • 0
Since our recent move to Lightning, we've lost the ability to use the Contact Roles feature on our Accounts. 

The given response from salesforce is to use the Account Contact Relationship object and add a checkbox called "Primary" (Primary__c)

This has been working well, but this unfortunetely doesn't prevent our sales reps from accidently selecting multiple primary contacts. 

I believe what I'm needing is a trigger on the AccountContactRelationship object that will prevent multiple people from being checked and display an error. 

I've found a few trigger codes that say they work, but all seem to error out when complied in my sandbox org as I don't believe they were written for the AccountContactRelationship object
Hi Experts,

I need to calculate the Date of current week in apex class, i have two fields preferred date and WeekDate field , eg: when  'Preferred Day(picklist list field)” = Monday so i need to set to the date for the "WeekDate" field  to  Monday of this week like wise i need to do till friday. if Preferred Day value is none then i need to populate todays date for the WeekDate field.

Thanks indavance
I have a business case where I need to be able to report on the Mean Time between certain records based on some criteria.

Example: I have an object that tracks IT issues and they are prioritized 1 - 5 (1 being Severe to 5 being benign). I need to show Mean Time between the Priority 1 tickets and am struggling to pull that information into report format.

Any suggestions?
Hi,

I am trying to create a trigger which will be checking a checkbox automatically when another process is done.
In specific, I have a custom object Vacation Requests which follows an approval process. If the request is approved, a checkbox "Approved" is being checked.
Then I am creating a trigger which needs to check if the current date is = to the start date of the vacation. if yes, then the checkbox should be selected.
However this doesn't happen.
Any ideas?
trigger Vacation on Vacation_Requests__c (before insert) {
    User u = new User();
    for (Vacation_Requests__c vr:Trigger.new) {
        if (vr.Approved__c==true && vr.Start_Date__c==System.Today()) 
            u.On_Vacation__c=true;        
    }

}

 
Given I have an Opportunity and there are no open Mandatory sales tasks associated to it When I try and change the opportunity stage
then this shall be allowed by the system. Given I have an Opportunity and there are open Mandatory sales tasks associated to it
When I try and change the opportunity stagetThen the system shall throw a validation error.

trigger Opportunity_Task on Opportunity (before update) {
    List<Task> ts =new List<Task> ();
    List<Opportunity> op =new List<Opportunity>();
    Map<Id,Opportunity> oldMap = trigger.oldMap;
    Map<Id,Opportunity> newMap = trigger.newMap;
    List<id> optyid = new List<id>();
    for(id opid:oldMap.keySet()) {
        Opportunity op =new Opportunity();
        if(oldMap.get(opid).tasks == null && op.stageName=='Closed Won') {
            op.addError('You can create a new task for that Opportunity');
            task t = new task();
            t.WhatId=opid;
            t.Description='kjdkfhsdkf';
            t.Status='open';
            ts.add(t);
        }
        else{
            if(oldMap.get(opid).tasks!=null && op.StageName=='Closed Won')
            op.addError('You cannot modify the opportunity status');
            
        }
    }
    
}
How can task assignee get an email notification when there is an attachment added to the task?
Need to develop a batch which will create investment projects for all accounts having minimum one opportunity

NOTE : If already project available on account then we don't have to create new, if it not exist then create new project and run batch  with batch size 5. 


Thanks
amit
                 
Would like to create a class to POST some data on an endpoint provided by an outside vendor.  Am modeling it on the "Mighty Moose" Trailhead example (https://trailhead.salesforce.com/en/content/learn/modules/apex_integration_services/apex_integration_rest_callouts) and the only difference seems to be the endpoint, the existence of an "api_key" (which the vendor says should be part of the url), and am passing more than one field.  Looks simple, but I have never done this type of thing before.  

Am testing in the "Open Execute Anonymous Window" of the developer console.  The trailhead example works fine but I am always getting a 400 Bad Request error for the real call out.  I do have a Remote Site setting.

Anything in the code below you can see (some data changed for security reasons)?
Any code you think might work better?
Any questions or details I should ask the vendor?
The vendor says I should be getting an explanatory message, but in the debug log I only see '400 Bad Request' and some other seemingly unrelated stuff.
 
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://my.domain.com/icon/send_eligible_offers?api_key=abcd-1234');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json;charset=UTF-8');

// Set the body as a JSON object
request.setBody('{"product_sku":"NTL07007", "serial_number":"1234343434", "user_email":"user.name@gmail.com", "sales_person_email":"agent@mail.com"}');

HttpResponse response = http.send(request);

// Parse the JSON response
if (response.getStatusCode() != 201) {
    System.debug('The status code returned was not expected: ' +
        response.getStatusCode() + ' ' + response.getStatus());
} else {
    System.debug(response.getBody());
}

 
Hey there, I'm a web developer working with a salesforce developer. I have limited knowledge of SF but was hoping someone could help me point the developer we're working with in the right direction. 

Currently, we have a cron set up on our site every 30 minutes that uses the SOAP api to query 12 fields for around ~500 records to check for status changes due to new leads. This is super inefficient and also means that we are in some cases working with 29 minute old data that is problematic when course registrations are full but continue to allow registrations. 

If we could do away with our cron and instead have a script on our server be hit any time a new lead comes in that would prevent us from having to run a cron every 30 minutes to check 500 courses (many of which haven't changed since the last time). 

Here's what we're hoping is possible.

New lead comes in for a particular course number. 
SF hits https://ourUrl.com/new-lead.php?course_number=12345
We use the SOAP api to query course #12345 for the updated info. 

From looking through the docs and forums it seems like he should be able to accomplish this using triggers, future methods and/or outbound messaging. Am I pointing him in the right direction? 

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers.htm#!
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_invoking_future_methods.htm#!
https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_om_outboundmessaging.htm#!
  • January 30, 2019
  • Like
  • 1
Hey all, I'm a newbie...and studying toward Develop certification (App and Platform 1) ... may take most of the Winter and Spring? Longer? Does anyone have an interest in joining up in a small study group ("Study Buddies")... we could setup weekly (?) Zoom meetings... discuss lessons learned...help learn, etc.  I was hoping for 3-5 of us? Thanks 

 Jarrell
I have requirement to clear out the fields not included in the page layout when I switch from on record type to other. So lets say a record is created for record type 'A' and has 10 fields and when I change the record to record type 'B' which has 6 fields (all these 6 fields are subset of fields in RT 'A') then remaining 4 fields should 'null' out. I know I can do that with a trigger or process builder but in that case I would have to mention each and every field and its relative value. It would be a very long process so I was wondering if there is a simple funtion to do this?
  • March 27, 2018
  • Like
  • 1
I have three picklist values picklist1,picklist2,picklist3 all picklist containing values 1-10, based on these picklist values in have to highlight a section of a VF.I am trying to add picklist values so that values so that I can use them as standard for each section of VF page when combination falls in any one of the standard it should highlight that perticular section.
i am trying but couldn't get it done.can some one help me with that.
Thanks in advance.
Hello, 

I am wondering is anyone else has had this problem. When we are refreshing the dashboards, the dashboard just turns to code. It isn't anymore complicated than that. Literally, it is just html tags and styling. Does anyone know why this might be? 

Thanks.
If you look at the general approach to write a batch, it asks to implement the Batchable interface. The sample code is like this -
global class Accountupdate implements Database.Batchable<sObject> 
{ 
:
:
Here, one thing is absurd - what is the use of datatype sObject in the interface name? Can we write an interface like this?
Also, Salesforce doc says you need to implement start method -
global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}
But in an interface how can you define a method with 2 return types? Again, when you actually implement this, you are implementing with just any one of these return types - Database.QueryLocator or Iterable<sObject>. How does this work?

In a nutshell, how has salesforce written the Batchable interface?
 
Hello Everyone, Hope all are doing good i have some information for you all go through it and give me a reply for that!

Amazon EC2 (AWS Certified)is an Infrastructure as a Service which offers pay-by-hour servers (EC2), storage (S3) etc. You bring your own software to the table – OS (Red Hat, Windows, whatever), Database (MySQL, Oracle, DB2, whatever), Search (your pick), Business Intelligence (Cognos, Oracle BI, whatever) – and then you piece it together and get it all to work. The benefits are that you can do whatever you want – and the con is you have to manage complexity yourself.

Force.com, by contrast, is a Platform as a Service that provides a pre-integrated offering that already has a database, search, BI Reports, identity/security etc. all built in – that you program using a Java-like language (Apex). With the newly announced VMforce, a VMware and Salesforce.com offering, you will be able to use Java soon. Force.com automatically backs up your data, manages upgrades (your apps don’t need to know if Force.com is running on database version 11i or 11g, Dell boxes or Sun boxes, Linux or Windows etc.)

Regards
Sarahjohn
Hi All,
          I just want to understand if "Attempt to schedule too many concurrent batch jobs in this org" occurs in below scenario ?

          Let's say I have 2 schedulable batch jobs schedulbatch1 and scheulbatch2.
          Schedulebatch1 has 10 batch apex jobs and schedulebatch2 has 2 batch apex jobs.

          I will schedule schedulablebatch1 at 12 AM and schedulable batch2 at 1AM.
         
          During execution of schedulablebatch1, any chances that I get this error ? 
          Or,iff schedulablebatch1 is not finished before 1 AM and schedulablebatch2 starts execution will I get this error ?
                  
         I read that at a time not more than 5 batch apex jobs can be processed.
    
           global class schedulebat implements schedulablebatch1 {
                global void execute (schedulablecontext sc){
                    
                   batchapex1 bat1 = new batchapex1();
                   database.executable(bat1);

                   batchapex2 bat2 = new batchapex2();
                   database.executable(bat2);

                   batchapex3 bat3 = new batchapex3();
                   database.executable(bat3);

                   batchapex4 bat4 = new batchapex4();
                   database.executable(bat4);

                   batchapex5 bat5 = new batchapex5();
                   database.executable(bat5);

                   batchapex6 bat6 = new batchapex6();
                   database.executable(bat6);

                   batchapex7 bat7 = new batchapex7();
                   database.executable(bat7);

                   batchapex8 bat8 = new batchapex8();
                   database.executable(bat8);

                   batchapex9 bat9 = new batchapex9();
                   database.executable(bat9);

                   batchapex10 bat10 = new batchapex10();
                   database.executable(bat10);
}
}
Best Practice : When someone takes the time/effort to repspond to your question, you should take the time/effort to either mark the question as "Solved", or post a Follow-Up with addtional information.

User-added image


      That way people with a similar question can find the Solution without having to re-post the same question again and again. And the people who reply to your post know that the issue has been resolved and they can stop working on it. 

Thanks #Copy_Steve Molis
Is it possible to ensure an approval process's final approval/rejection unlocks the record before any of the field updates happen?

Ordinarily it seems like it doesn't especially matter, as field updates are somehow applied despite being locked, but I am running a trigger off those field updates that attempts to delete the record, but cannot because it is still locked.

As a workaround, I'm thinking my trigger can unlock the record before deleting it, but this seems to be a senseless complication.

Surely if there are field update actions, the record has to unlock first?
could any one explain even though i wrote standard controlller 
 <apex:page standardController="japan__c" recordSetVar="jap">
    <apex:dataTable value="{!jap}" var="a">
        <apex:column value="{!a.name}" />
    </apex:dataTable>
</apex:page>
User-added image
i am unable to see Visualforce in page layout. do i need enable anything in specific . 
Hello Everyone,
I am having a major problem.  I have no idea how to code and thus starts my issue.  I am trying to activate quantity and Revenue Scheduling for quotes as well as contract.  However, this isn't supported in lightning.  We do not want to pay for a App or hire a consultant.  We need an amount of samples input that have a standard price per sample; an amount of grams (that change price a certain milestones).  
When two accounts have been merged, the child Contact record that's reparented isn't getting updated with the new Account because it's not triggered to do so.  Apparently this is one of the operations that doesn't invoke a trigger automatically (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_ignoring_operations.htm), so I'm having to write one for this particular scenario.  I'm not very experienced at writing Apex Triggers so can someone please assist me in what that code would be?

Thanks in advance!
When I say debug log I am referring to the following screenshot:





User-added image
where can I find a resource that will teach me how to read this info.

Many Thanks.
Charlene.
Example is that a customer will send an email to 2 different teams at the same time as they are unsure who is best placed to answer their question.
They type in both email addresses in the TO: field in their email provider... ie test1@test.com, test2@test.com

When they send they will get 2 auto notifications with 2 different case reference numbers.

Can rules be set up to ignore all but the 1st email address in order to only create 1 case?

Otherwise, if it creates more a case for each email address, it will result in more work for everyone and confusion over who is responding etc
i want to create a new contact from Account detail page using custom links.and i want to display that particular Account name in that conatct lookup
Hello,

I have a scheduled apex class that uses the Last Modified Date in an SOQL query.  My problem is: when I create the Apex test class, I can't set the Last Modified Date to be in the past on the record that I am inserting for my test.  But when I do the insert it updates the Last Modified Date to the current date/time.  Does anyone know of a way of creating a test record where the created date and last modified date will be in the past?

Thinking of enabling #Communities for your customer? Then be aware of the current #Gotcha that the default Apex Classes that are created when you enable your first Community do not ALL have code coverage >75%.

What this means:
You can enable Communities in Production, however as soon as you attempt to migrate anything from a sandbox into Production that triggers all tests to be run (doesn't have to be just code), your migration will fail as three of the classes only have 33%, 20% and 21%.

Let me repeat that, you might only be migrating a bunch of new custom fields and page layouts and the Change Set (or Eclipse/ANT) will fail.

I hit this problem this week in a go-live deployment so had to update Apex Classes to achieve average total code coverage >75% in order to proceed with our deployment.

The PM of Communities knows about the problem and advises he is looking at a fix, but in the meantime here are the four Apex Classes that need to be updated.

 

CommunitiesLandingControllerTest.cls

Just a one liner for this test class

/**
 * An apex page controller that takes the user to the right start page based on credentials or lack thereof
 */
@IsTest public with sharing class CommunitiesLandingControllerTest {
  @IsTest(SeeAllData=true) public static void testCommunitiesLandingController() {
    // Instantiate a new controller with all parameters in the page
    CommunitiesLandingController controller = new CommunitiesLandingController();

    // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    PageReference pageRef = controller.forwardToStartPage();
  }
}

 

CommunitiesLoginControllerTest.cls

Just a one liner for this test class

/**
 * An apex page controller that exposes the site login functionality
 */
@IsTest global with sharing class CommunitiesLoginControllerTest {
  @IsTest(SeeAllData=true) 
  global static void testCommunitiesLoginController () {
    CommunitiesLoginController controller = new CommunitiesLoginController ();

    // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    PageReference pageRef = controller.forwardToAuthPage();
  }  
}

 

CommunitiesSelfRegControllerTest.cls

A few controller variables to set prior to calling the controller method for the original test method, followed by a couple of additional test methods for further coverage.

/**
 * An apex page controller that supports self registration of users in communities that allow self registration
 */
@IsTest public with sharing class CommunitiesSelfRegControllerTest {
  @IsTest(SeeAllData=true) 
  public static void testCommunitiesSelfRegController() {
    CommunitiesSelfRegController controller = new CommunitiesSelfRegController();

    // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    controller.firstName = 'Bob';
    controller.lastName = 'Jones';
    controller.email = 'bob@jones.com';
    controller.password = '8yhMsHDN&ituQgO$WO';
    controller.confirmPassword = '8yhMsHDN&ituQgO$WO';
    controller.communityNickname = 'bob-jones-testing';

    PageReference pageRef = controller.registerUser();
  }
  // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
  @IsTest(SeeAllData=true) 
  public static void testInvalidPassword() {
    CommunitiesSelfRegController controller = new CommunitiesSelfRegController();
    controller.firstName = 'Bob';
    controller.lastName = 'Jones';
    controller.email = 'bob@jones.com';
    controller.password = '8yhMsHDN&ituQgO$WO';
    controller.confirmPassword = 'not the same';
    controller.communityNickname = 'bob-jones-testing';

    PageReference pageRef = controller.registerUser();
    System.assert(pageRef == null, 'The returned page reference should be null');
  }
  // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
  @IsTest(SeeAllData=true) 
  public static void testNullPassword() {
    CommunitiesSelfRegController controller = new CommunitiesSelfRegController();
    controller.firstName = 'Bob';
    controller.lastName = 'Jones';
    controller.email = 'bob@jones.com';
    controller.communityNickname = 'bob-jones-testing';

    PageReference pageRef = controller.registerUser();
    System.assert(pageRef == null, 'The returned page reference should be null');
  }
}

 

CommunitiesSelfRegController.cls

A few additions to this class to set the Profile and Account Ids for portal user creation. Update the ProfileId value based on the "portal" license(s) (e.g., Customer Portal, Customer Community, etc) and set the AccountId to that of the Account you wish to use for self-registration. Note: this needs to be set even if you're not using self-registration so the class can be tested.

Plus some debug statements so I could see what was happening and needed to be tested.

/**
 * An apex page controller that supports self registration of users in communities that allow self registration
 */
public with sharing class CommunitiesSelfRegController {

  public String firstName {get; set;}
  public String lastName {get; set;}
  public String email {get; set;}
  public String password {get; set {password = value == null ? value : value.trim(); } }
  public String confirmPassword {get; set { confirmPassword = value == null ? value : value.trim(); } }
  public String communityNickname {get; set { communityNickname = value == null ? value : value.trim(); } }
  
  public CommunitiesSelfRegController() {}
  
  private boolean isValidPassword() {
    return password == confirmPassword;
  }

  public PageReference registerUser() {
  
    // it's okay if password is null - we'll send the user a random password in that case
    if (!isValidPassword()) {
      System.debug(System.LoggingLevel.DEBUG, '## DEBUG: Password is invalid - returning null');
      ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, Label.site.passwords_dont_match);
      ApexPages.addMessage(msg);
      return null;
    }  

    // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    //String profileId = ''; // To be filled in by customer.
    //String roleEnum = ''; // To be filled in by customer.
    //String accountId = ''; // To be filled in by customer.

    // Set this to your main Communities Profile API Name
    String profileApiName = 'PowerCustomerSuccess';
    String profileId = [SELECT Id FROM Profile WHERE UserType = :profileApiName LIMIT 1].Id;
    List<Account> accounts = [SELECT Id FROM Account LIMIT 1];
    System.assert(!accounts.isEmpty(), 'There must be at least one account in this environment!');
    String accountId = accounts[0].Id;
    
    String userName = email;

    User u = new User();
    u.Username = userName;
    u.Email = email;
    u.FirstName = firstName;
    u.LastName = lastName;
    u.CommunityNickname = communityNickname;
    u.ProfileId = profileId;
    
    String userId = Site.createPortalUser(u, accountId, password);
   
    if (userId != null) { 
      if (password != null && password.length() > 1) {
        System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation successful and password ok - returning site.login');
        return Site.login(userName, password, null);
      }
      else {
        System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation successful but password not ok - redirecting to self reg confirmation');
        PageReference page = System.Page.CommunitiesSelfRegConfirm;
        page.setRedirect(true);
        return page;
      }
    }
    System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation not successful - returning null');
    return null;
  }
}