• Sanjana_singh12
  • NEWBIE
  • 0 Points
  • Member since 2021

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 5
    Replies
Hello,
I am a newbie in salesforce and practicing apex triggers using the following scenerio.
Pre-Reqs:
Create a field on Account called “Only_Default_Contact”, checkbox, default off
Assignment:
When a new Account is created, create a new Contact that has the following data points:
First Name = “Info”
Last Name = “Default”
Email = “info@websitedomain.tld”
Only_Default_Contact = TRUE
When the Account has more than 1 Contact, update Only_Default_Contact to FALSE.

So far I have only been able to create contacts related to account after insert. But, since I know that after insert, Account becomes read only. I needed a way to update the Only_Default_Contact__c field. 
Below is what I have tried but it does not seem to work. 

trigger createAccount on Account (after insert,before update)
{
   List<Contact> lst = new List<Contact>();
    Contact con = new Contact();
    if(trigger.isAfter && trigger.isInsert)
  {
   for(Account acc:trigger.new)
   {
     con.AccountId = acc.Id;
     con.FirstName = 'Info';
     con.LastName = 'Default';
     con.Email = 'info@websitedomain.tld';
     
     lst.add(con);    
   }
  }
   if(!lst.isEmpty())
   {
      insert lst;
   
   }
   
   
   if(trigger.isBefore && trigger.isUpdate)
   {
   List<Account> ls = [Select Only_Default_Contact__c from Account];
   for(Account a: trigger.new)
     {
      if(lst.size()==1)
        {
        a.Only_Default_Contact__c = TRUE;
        update a;
        }
        else
        {
          a.Only_Default_Contact__c = FALSE;
          update a;
        }
   }
   }
}