function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
DevelopementDevelopement 

Need Help

Hello, 

I am new to APex code and recently I wrote basic triggers.Now I started working on SOQL but am not sure how to start the syntax.

Suppose I have two object Account and Opportunities and I hav a field 'Count_ops' on Account which take the count of Opps and I want to update the field whenever new opportunity is created on this account.

So how to write trigger for it using sosql?

I tried this way:

 

trigger counts on Account (before insert) {
Account acc=trigger.new[];
count_opps=[selct count() of Opportunity where account.id=opportunity.id];

}

 

Please help me to understand the syntax......

 

 

Also I have seen that people uses list and sets to store data of query, when and why to use that? I am so confused  :(

kcpluspluskcplusplus
trigger counts on Opportunity(after insert,after update, after undelete, after delete) {
//clean list to add acc id too
LIST<ID> acctID = new LIST<ID>(); 
    //is the trigger context an insert
    if(trigger.isInsert){
        //loop through the opportunity id's in the new array   
        for(Opportunity o : trigger.new){
            //add the new opportunity account id to the list
            acctID.add(o.AccountId); 
            }
        }
     //is the trigger context an update - same as above except for update
    if(trigger.isUpdate){
        for(Opportunity o : trigger.old){
            acctID.add(o.AccountId);
            }
        }
    //new list for the acct that the opportunities are associated to
    LIST<Account> acct = [SELECT id FROM Account WHERE ID IN :acctID];
    //list of opportunities with the account as the parent id
    LIST<Opportunity> oppty = [SELECT id FROM Opportunity WHERE AccountId IN :acctID];
    //clean list for accounts to update
    LIST<Account> updateAcct = new LIST<Account>(); 
    //loop through accounts being updated
    for(Account a : acct){
        //get the size of the opportunity list
        Integer count = oppty.size(); 
        //if the count is not equal to 0
        if(count != 0){
            //assign the count to the count field on account
            a.count__c = count; 
            //add the record to the account list to update
            updateAcct.add(a); 
        }
        //update the account
        update a; 
    }
 
    
}
 

 Try this, that way the roll up will also react to updated opptys, as well as deletes and undeletes. 

 

--KC

Abhishek_NewAbhishek_New

Hi,

 

I am also new to salesforce and Apex..I also have done the trigger practice..Only the difference is that..I used contacts object whereas U used oppertunity object...I hope the following code is a simple one..Try this out..Hope we both are learning good..

 

trigger UpdateContactNo on Contact (after insert,after update) {
list<Account> acc = new list<Account>();
for(Contact c:trigger.new)
{
list<Account> ac = new list<Account>();
ac = [select id,No_of_Contacts__c from Account where id =: c.AccountId];
for(Account a : ac)
{
if (a.No_of_Contacts__c != null){
a.No_of_Contacts__c = a.No_of_Contacts__c+1;
acc.add(a);
}
else{
a.No_of_Contacts__c = 1;
acc.add(a);
}
}
}
try
{
if(!acc.isEmpty())
update acc;
}
catch(Exception e)
{
e.getMessage();
}

}

vishal@forcevishal@force

Hi,

 

Before digging into Triggers, I would like to know if counting the Opportunities is your only requirement?

 

If yes, you can do so using a Rollup Summary field.

 

Details here : Roll up Summary fields

 

You simply need to create a new field on Account of type Roll up Summary, select object as Opportunity and select the aggregate function as "Sum". Optionally you can also add a filter if you need to do so while counting the related Opportunities.

DevelopementDevelopement

Hello,

Actually I think I was not clear to my question.I can explain it this way:

 

One Object: Opportunity

Other Object: Cases

 

Scenario: Cases has status "New, Sales, Closed". Cases is not related to opp but related to Accounts object.[Account and Opportunity are related] 

I have created a field on Opportunity and I want that whathever is the status of Case, it should populate on the Opportuity object in the field i  created.

Could you please tell me how to write a trigger based on the above scenario.

 

Thanks a lot!

DevelopementDevelopement

Hi Vishal,

I have idea about roll up summary but am trying to learn the trigger using Query.I have posted gaian my question . Hope you will help me to resolve the query.

 

Thanks,

DevelopementDevelopement

I tried writing  a trigger but am stuck that how to match the account ID to the account Id on case to get the case status.

But I need to update the filed on Opportunity and Opportunity laos has account name.

 

this is the relation

Case-> Account

Account-> Opp

 

 

trigger Updateopp on Opportunity (after insert,after update) {
list<Cases> ca = new list<Cases>();
for(Cases c:trigger.new)
{
list<Cases> caa = new list<Cases>();
ca = [select Status from Cases where id =: c.AccountId];

 

 

Please help!

Abhishek_NewAbhishek_New

Need some info from you..

 

An account can contain many Cases as well as many oppertunities.which case's status you want to populate in which oppertunity's field ?Its bit confusing.How are you relating these 2 objects' records?

 You can give a Look up field in oppprtunity having Case lookup.Then you can relate..

 

Please correct me if I am wrong.New to salesforce.

DevelopementDevelopement

Hello Abhishek,

In my organization, its kind of one to one.. One case to one account and one opp to on eaccount.

I cannot create the lookup field because I want its to be auto poupulated and using that status I will be creating the validation rules.

Let me know if you can help to create trigger for that.

Abhishek_NewAbhishek_New

Hope this will help you out....Only difference I have created CaseStatus field in opportunity whereas you can define your your required fields based on Case Status..

 

trigger OppTrigger on Opportunity (before insert,before update)
{
      set<ID> id1 = new set<id>();
    for(Opportunity opp:trigger.new)
      {
         id1.add(opp.Accountid);
      }
        map<id,Account> mp =new map<id,Account>([select id,name from account where id in:id1]);
        List<Case> caseLst = [select id,status,AccountId from case where Accountid=:mp.keyset()];
        map<id,case> caseAccMap=new map<id,case>();
     for(Case c: caseLst)
        {
            caseAccMap.put(c.AccountId,c);
        }
       
    for(Opportunity opp:trigger.new)
         {
                if(caseAccMap.keySet().contains(opp.Accountid))
                {
                    opp.CaseStatus__c = caseAccMap.get(opp.AccountId).status;
                }
         }                   

 

DevelopementDevelopement

Hi Abhishek,

Thanks the above triggers work but I think I missed some part.

 

I have 4 objects and their relatinoship is like this:

Case-> Account

Opportunity->Account

Case->Caseopp

Caseopp-> Opportunity

 

I have created a new field on Opportunity as  " Test". 

what am trying to do is I need to copy the status of Case on this field "Test" only on those Opportunity which exists on Caseopp by trigger.