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
MlearyMleary 

Help with Trigger - update field on Contact with Change on Account

Hey Everyone - I am new ot the developer community and just getting my feet wet with learning Apex Code.  Could someone steer me in the right direction with the below requested automation?

 

Here is the scenario ---

When checkbox field Custom_Feild_A__c is marked true on Account

Two checkbox fields are updated on the Contact:
Custom_Feild_B__c is marked true
Custom_Feild_C__c is marked true




I have tested this several times but after checking the box on the account the two checkbox fields on the Contact remained unchecked?

Best Answer chosen by Admin (Salesforce Developers) 
Noam.dganiNoam.dgani

Hi Mleary

 

Is this the standard relationship between account and contact?

if so, which contact do you want to update under the account?

 

lets assume that you want all contacts related to the account, your code should be:

 

trigger YOUR_TRIGGER_NAME on ACCOUNT (after update) {
	
	set<Id> accIds = new set<Id>();
	
	for(Account acc: trigger.new)
	{
		if(acc.Custom_Feild_A__c && !trigger.oldMap.get(acc.Id).Custom_Feild_A__c)
		{
			accIds.add(acc.Id);
		}
	}
	
	if(!accIds.isEmpty())
	{
		List<Contact> update_contacts = new List<Contact>();
		for(Contact con : [select Id,Custom_Feild_B__c,Custom_Feild_C__c from Contact where AccountId IN: accIds])
		{
			if(!con.Custom_Feild_B__c && !con.Custom_Feild_C__c)
			{
				con.Custom_Feild_B__c = con.Custom_Feild_C__c = true;
				update_contacts.add(con);
			}
		}
		
		if(!update_contacts.isEmpty())
		{
			update update_contacts;
		}
	}
}

 

 

Hope this helps - if it does, kindly mark it as resolved.

All Answers

Noam.dganiNoam.dgani

Hi Mleary

 

Is this the standard relationship between account and contact?

if so, which contact do you want to update under the account?

 

lets assume that you want all contacts related to the account, your code should be:

 

trigger YOUR_TRIGGER_NAME on ACCOUNT (after update) {
	
	set<Id> accIds = new set<Id>();
	
	for(Account acc: trigger.new)
	{
		if(acc.Custom_Feild_A__c && !trigger.oldMap.get(acc.Id).Custom_Feild_A__c)
		{
			accIds.add(acc.Id);
		}
	}
	
	if(!accIds.isEmpty())
	{
		List<Contact> update_contacts = new List<Contact>();
		for(Contact con : [select Id,Custom_Feild_B__c,Custom_Feild_C__c from Contact where AccountId IN: accIds])
		{
			if(!con.Custom_Feild_B__c && !con.Custom_Feild_C__c)
			{
				con.Custom_Feild_B__c = con.Custom_Feild_C__c = true;
				update_contacts.add(con);
			}
		}
		
		if(!update_contacts.isEmpty())
		{
			update update_contacts;
		}
	}
}

 

 

Hope this helps - if it does, kindly mark it as resolved.

This was selected as the best answer
MlearyMleary

Yes you were correct in assuming that I needed all associated Contacts and that they have a standard relationship.  I will work on this now and will let you know the outcome!  Thank you so much!

Noam.dganiNoam.dgani

so just change the fields in the trigger i wrote to your own fields - and your set.

SFAdmin5SFAdmin5

you don't need code for this i don't think.

 

just use a formula field and workflow.

 

create your checkbox field a on account, and checkbox fields b and c on contact

 

then create hidden formula field (type text) on contact as well with a formula like this (change field names if you like)

 

IF( 
Account.Custom_Field_A__c = true, 
"1","0" 
)

 

Then createe workflow rule on contact with 2 field updates on checkboxes b and c on create or edited and did not previously meet criteria,  setting them to true.

 

always use config over code if possible (unless I misunderstand the reqs here)

Noam.dganiNoam.dgani
Formula field changes do not fire workflows or triggers.
SFAdmin5SFAdmin5

yes they do.  I just did it in a dev org

MlearyMleary

I put in the trigger as you wrote it, inserted my custom fields, and then recieved this error message:

 


Error: Compile Error: unexpected token: Suppression at line 1 column 12

Noam.dganiNoam.dgani
Ok. So that would be simpler.
Try it. They don't fire for me...
Noam.dganiNoam.dgani
Post the complete trigger code.
It's hard to tell what is the problem without seeing it.
MlearyMleary

Sure thing!

 

trigger ROI Suppression on ACCOUNT (after update) {

   

    set<Id> accIds = new set<Id>();

   

    for(Account acc: trigger.new)

    {

        if(acc.ROI_Suppression__c && !trigger.oldMap.get(acc.Id).ROI_Suppression__c)

        {

            accIds.add(acc.Id);

        }

    }

   

    if(!accIds.isEmpty())

    {

        List<Contact> update_contacts = new List<Contact>();

        for(Contact con : [select Id,ROI_Automation_Suppression__c,Custom_Feild_C__c from Contact where AccountId IN: accIds])

        {

            if(!con.ROI_Automation_Suppression__c && !con.ROI_Suppression__c)

            {

                con.ROI_Automation_Suppression__c = con.ROI_Suppression__c = true;

                update_contacts.add(con);

            }

        }

       

        if(!update_contacts.isEmpty())

        {

            update update_contacts;

        }

    }

}

sbbsbb

Get rid of the space between 'ROI' and 'Suppression' in your trigger name.

SFAdmin5SFAdmin5

i just double checked my work and you can definitely do this with 1 workflow rule w. 2 workflow field updates and a formula field.

 

Step 1.  create your fields:

 

on account:

 

Custom Field A (checkbox)

 

on contact:

 

Custom Field B (checkbox)

Custom Field C (checkbox)

Hidden_Field__c (Formula of type text with this formula: 

 

IF( 
Account.Custom_Field_A__c = true, 
"1","0" 
)

 

Step 2. Create your workflow and 2 field updates

 

Create Workflow Rule:
Worfkflow Rule should be on Contact object and should fire every time a record is created or edited and did not previously meet the rule criteria

 

Workflow Rule crtieria: 

 

Contact: Hidden Field EQUALS 1

 

Create Workflow Rule Field updates (2):

 

field update#1: Set Contact.Custom Field B (checkbox) to "True"

field update#2: Set Contact.Custom Field C (checkbox) to "True"

 

Activate workflow rule.

 

How does that not work?

 

 

Noam.dganiNoam.dgani
Because salesforce evaluates formula fields when they are needed (meaning when they are rendered in layout, queried etc).
Same reason why you can't perform history on them.
But, maybe it changed since I last checked.
Are you sure you don't have something else that updates the contacts wen the account is updated and the workflows just "hitch a ride" on that update?
SFAdmin5SFAdmin5

yeah this definitely works with the formula and workflow.  no code should be needed at all; you are right that it didn't used to work, though.  i know you definitely could not use a formula field in wfr crtieria before, but you definitely can now.  i'm pretty sure sf changed this so you can do this now.  

 

i've got no other logic that could possibly be doing this.  it works

Noam.dganiNoam.dgani

That is awesome News SFAdmin5.

i can probably get rid of a few triggers now.

 

thanks for the tip.

Noam.dganiNoam.dgani

got me interested - so I tried it.

it doesn't work for me.

 

here is what I did:

  1. Formula of type text on contact saying if account.name = 1 formula is "true" else "false"
  2. workflow on contact every time record is created or edited and did not previously... That asks if formula field equals "true" perform a field update on first name and changes it to something.
  3. create account and contact. Account name is not equal 1
  4. update account name to 1 
  5. no update on ccontact

what do you think is wrong SFAdmin5?

 

SFAdmin5SFAdmin5

good call.  the workflow and formula solution only works on account record insert having Custom Field A being set to true.

 

if the requirement is that accounts will always get that checkbox on record create and not in a later update this still works.

 

but this get me thinking...wouldn't the simplest solution here be to just have the custom field a checkbox on the account, and then have custom fields b and c on the contacts be 2 formula fields that output a text yes or no, like this

 

IF( 
Account.rossg10242012__Custom_Field_A__c = true, 
"Yes","No" 
)

 

Unless someone has some reason that checkbox fields b and c must be checkboxes (not sure what that could be but there might be a reason I can't think of), then that would work I believe.

 

but if all 3 fields need to be checkboxes, and if the account can get updated later after creation with checkbox a = true, then you are definitely correct that the trigger is the only way to go here.

 

just trying to find a way around this without code since there is so much in config between contacts and accounts that you can do already.

MlearyMleary

Hi Ross!

 

There could be situations where checkboxes B and C on the Contact could be checked, but the Account Checkbox A is unchecked.  But never will the Account Checkbox A be checked without all related Contact checkboxes B and C also being checked.  So that is why the checkboxes on the Contact need to remain checkbox fields as opposed to formula fields.

 

The trigger provided by Noam.dgani does work for me!  So I will close the post.   

But I wasn't quite following why the formula field + workflow rule won't work.  Just for my understanding, are you saying that it will only work upon record creation?

MlearyMleary

Oh brother,  I don't know how to write a test script.  Any direction or help you could give me here?

SFAdmin5SFAdmin5

this trigger and test class ought to work

 

Trigger accountTrigger on Account (after update,after insert ){
    List<Contact> contactsToUpdate = new List<Contact>();
    for(Contact contact :[select Id, Custom_Feild_B__c, Custom_Feild_C__c from Contact where Account.Custom_Feild_A__c = true AND AccountId in : trigger.new]){
        contact.Custom_Feild_B__c = true;
        contact.Custom_Feild_C__c = true;        
        contactsToUpdate.add(contact);
    }

    if(!contactsToUpdate.isEmpty())
        update contactsToUpdate ;

}

 

public class testAccountTrigger {

    static testMethod void testAccountTrigger(){

    Profile pf = [Select Id from Profile where Name = 'Standard User'];
 
        User u = new User();
        u.FirstName = 'Test';
        u.LastName = 'User';
        u.Email = 'testuser@test123456789.com';
        u.CompanyName = 'test.com';
        u.Title = 'Test User';
        u.Username = 'testuser@test123456789.com';
        u.Alias = 'testuser';
        u.CommunityNickname = 'Test User';
        u.TimeZoneSidKey = 'America/Mexico_City';
        u.LocaleSidKey = 'en_US';
        u.EmailEncodingKey = 'ISO-8859-1';
        u.ProfileId = pf.Id;
        u.LanguageLocaleKey = 'en_US';
        insert u;
 
        system.runAs(u){
                                
        Account acct = new Account();
        acct.Name = 'test';
        acct.Custom_Feild_A__c = false;
        insert acct;       
        
        Contact ct = new Contact();
        ct.LastName = 'test';
        ct.Custom_Feild_B__c = false;
        ct.Custom_Feild_C__c = false;
        ct.AccountId = acct.Id;
        insert ct;
                 
        acct.Custom_Feild_A__c = true;
        update acct; 
        
        System.debug(ct.Custom_Feild_B__c);
        System.debug(ct.Custom_Feild_C__c);
                   
        for(Contact con: [Select Id,Custom_Feild_B__c,Custom_Feild_C__c from Contact where Id =: acct.Id])
        
        {       
        
        System.assertEquals(true, con.Custom_Feild_B__c);
        System.assertEquals(true, con.Custom_Feild_C__c);
        
        }
        
        }
        
    }
        
}