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
Soubhagya Ranjan 2Soubhagya Ranjan 2 

errorin trigger

Hi I am having this trigger . when my account name is already present status will updated as Y . and when address is already present then its not updating to Y .. why ?

trigger accountupdatestatus1 on Account (before insert) {
  list<account> acc = new list<account>(); 
  list<account> acc1 = new list<account>();
 for(account a: trigger.new)
 {
acc=[select id,name from account where name=:a.name];
  if(acc.size()>0)
  {
   a.Status__c = 'Y' ;
  }
 }
 for(account a1: trigger.new)
 {
acc1=[select id,name,BillingStreet from account where name=:a1.BillingStreet];
  if(acc1.size()>0)
  {
   a1.Status__c = 'Y' ;
  }
 }
}
Ajinkya1225Ajinkya1225
Soubhagya,

Couple of things before you approach this problem-
  1. Account Name field is mandatory. So, your condition should have been if (a.BillingStreet != '') to change the status
  2. You have written SOQL queries in for loop. Its a poor practice. You would get Error 101 if you use bulk imports.
Hint: If you follow step 1, you need only 1 for loop! Give it a try, you are not able to resolve, I'm happy to help.

Can you take a moment to  upvote and mark this answer as solved, if it helped you.
Cheers!
Ajinkya Deshmukh
Soubhagya Ranjan 2Soubhagya Ranjan 2
there are 2 different requirement
1 - when account name present then insert the record and update status as Y 
2- when address is present then insert the record and update status as Y

could you please change the code so that i can get a good idea how to query outside for loop
Ajinkya1225Ajinkya1225
In both cases you have to update the address to Y? Your point 1 is always going to be true. In a subset of cases point 2 will be true. And you are updating the status to be same?

This should work-
 
Trigger AccountTrigger on Account(before update, before insert){
    for (Account eachAccount : trigger.new){
        if (eachAccount.BillingStreet != '') {
            eachAccount.Status = 'Y';
        }
        else {
            // no matter when the record is inserted, this step would be executed
            eachAccount.Status = 'Y';
        }
    }
}

Note: Put some condition in the else block below, else your status would always be Y


Can you take a moment to  upvote and mark this answer as solved, if it helped you.
Cheers!
Ajinkya Deshmukh