Activity › Forums › Salesforce® Discussions › How to create trigger using apex class to count the no of contacts?
-
How to create trigger using apex class to count the no of contacts?
Posted by pawan makkar on November 30, 2017 at 7:23 AMIn Salesforce, how to create trigger using Apex class to count the number of contacts?
Rajan replied 8 years, 4 months ago 3 Members · 2 Replies -
2 Replies
-
This example shows Apex to create an ApexPage, but from python it will be a matter of sending the request to the correct endpoint.
You’ll need to send a JSON payload to the correct enpoint with the correct details, for ApexTrigger see here: http://www.salesforce.com/developer/docs/api/Content/sforce_api_objects_apextrigger.htm
private void setRestPostUrl(){
String sfdcUrl = (String)URL.getSalesforceBaseUrl().toExternalForm();
String apiPath = ‘/services/data/v30.0/sobjects/ApexPage’;
restPostUrl = sfdcUrl+apiPath;}
sfdcURL would be: “naXX.Salesforce.com”, where XX is the instance (na1, na2, na3…)
apiPath: the last part ‘ApexPage’ is what you’ll need to modify. For Triggers: ApexTrigger, for classes: ApexClass.So you’ll need your OAuth token, and send your payload to: https://na10.salesforce.com/services/data/v30.0/sobjects/ApexTrigger
(You’ll set a Header as ‘Authorization’ with the OAuth token.) - [adinserter block='9']
-
Using Apex classes——————
public class mytriggercount{
public static void counttrigger(contact [] cts){
set<id> accidlist = new set<id>();
for(contact con:cts){
accidlist.add(con.Accountid);
}
list<account> acc = new list<account>();
for(Account a:[select id,my_contacts__c,(select id from contacts)from Account where id IN:accidlist]){
a.my_contacts__c = a.contacts.size();
acc.add(a);
}
update acc;
}
}trigger——————————-
trigger countcontacts1 on Contact (after insert,after update,after delete,after undelete) {
if(trigger.isafter){
if(trigger.isinsert){
mytriggercount.counttrigger(trigger.new);
}
}
if(trigger.isafter){
if(trigger.isundelete){
mytriggercount.counttrigger(trigger.new);
}}
if(trigger.isafter){
if(trigger.isupdate){
mytriggercount.counttrigger(trigger.new);
}
}
if(trigger.isafter){
if(trigger.isupdate){
mytriggercount.counttrigger(trigger.old);
}
}
if(trigger.isafter){
if(trigger.isdelete){
mytriggercount.counttrigger(trigger.old);
}
}
}
Log In to reply.