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
Vishal KashyapVishal Kashyap 

Error in trigger

After writing this trigger when I create an acount I get the error message 

 

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger CountAcc caused an unexpected exception, contact your administrator: CountAcc: execution of AfterInsert caused by: System.QueryException: List has no rows for assignment to SObject: Trigger.CountAcc: line 9, column 1

 

Also can anybody please tell me how to do the update operation outside for loop?

 

 

trigger CountAcc on Contact (after insert){
    List<contact> NCL = trigger.new; 
    String AccountName;
        
    for(Contact C:NCL)
    {
        AccountName=C.AccountID;
        Account A=new Account();
        A=[Select noc__C from Account where ID=:AccountName];
        A.noc__C++;
        Database.update(A);
     }
}

 

Vinit_KumarVinit_Kumar

Vishal,

 

Please try below

 

Trigger CountAcc on Contact (after insert){
List<contact> NCL = trigger.new;
Id AccountName = new Id();

for(Contact C:NCL)
{
AccountName=C.AccountID;
Account A=new Account();
A=[Select noc__C from Account where ID=:AccountName];
A.noc__C++;
Database.update(A);
}
}

AnwarAnwar

Dont use soql in for loop

the salesforce hit the governer limits

Vinit_KumarVinit_Kumar

Agreed with @anwar,I did not notice that,Please find below the updated code.

 

Trigger CountAcc on Contact (after insert){
List<contact> NCL = trigger.new;
List<Id> AccountName = new List<Id>();

for(Contact C:NCL)
{
AccountName.add(C.AccountID);
}

List<Account> AccList=new List<Account>();
AccList=[Select noc__C from Account where ID in:AccountName];
for(Account a:accList){
A.noc__C++;
Database.update(A);
}
}

AnwarAnwar

Please Post the  requerment, I will write a trigger

Thanks

Anwar