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
Rogerio Lara 2028Rogerio Lara 2028 

uncheck box based on new related record created

Hi there, Please Help! ;-)

I have a checkbox field that is by default checked when a record is created. (Good)

Let's suppose I have a custom object that relates to the Opportunity object, then I create record1 under the Opportunity (related list).

When I then create record2, I need the check box on record1 to be automatically unchecked.

Please can someone help me with the trigger. I don't really even know where to start ;-(

Thank you,

Rog
Best Answer chosen by Rogerio Lara 2028
Nayana KNayana K
Lets assume custom obj name is RelatedObj.

trigger RelatedObjTrigger on RelatedObj__c(before insert, after insert)
{
	RelatedObjHandler objHandler = new RelatedObjHandler();

	if(trigger.isBefore)
	{
		if(Trigger.isInsert)
		{
			objHandler.onBeforeInsert(Trigger.New);
		}
	}
	if(trigger.isAfter)
	{
		if(Trigger.isInsert)
		{
			objHandler.onAfterInsert(Trigger.NewMap);
		}
	}
}

public class RelatedObjHandler
{
	// replace Opportunity__c, checkboxfld__c with actual API names

	
	public void onBeforeInsert(List<RelatedObj__c> lstNewRelatedObj)
	{
		Set<Id> setOppId = new Set<Id>();
		for(RelatedObj__c objRelatedObj : lstNewRelatedObj)
		{
			objRelatedObj.checkboxfld__c = true;
		}
	}
	
	public void onAfterInsert(Map<Id,RelatedObj__c> mapNewRelatedObj)
	{
		Set<Id> setOppId = new Set<Id>();
		List<RelatedObj__c> lstRelatedObjToUpdate = new List<RelatedObj__c>();
		for(RelatedObj__c objRelatedObj : mapNewRelatedObj.values())
		{
			
			if(objRelatedObj.Opportunity__c != NULL)
				setOppId.add(objRelatedObj.Opportunity__c);
		}
		
		// fetch old related obj records of parent opportunity and set checkbox to false
		for(RelatedObj__c objRelatedObj : [SELECT Id, checkboxfld__c 
											FROM RelatedObj__c
											WHERE Id NOT IN : mapNewRelatedObj.keySet()
											AND Opportunity__c IN: setOppId])
		{
			objRelatedObj.checkboxfld__c = false;
			lstRelatedObjToUpdate.add(objRelatedObj);
		}
		
		if(!lstRelatedObjToUpdate.isEmpty())
			update lstRelatedObjToUpdate;
	}
}

 

All Answers

Nayana KNayana K
Lets assume custom obj name is RelatedObj.

trigger RelatedObjTrigger on RelatedObj__c(before insert, after insert)
{
	RelatedObjHandler objHandler = new RelatedObjHandler();

	if(trigger.isBefore)
	{
		if(Trigger.isInsert)
		{
			objHandler.onBeforeInsert(Trigger.New);
		}
	}
	if(trigger.isAfter)
	{
		if(Trigger.isInsert)
		{
			objHandler.onAfterInsert(Trigger.NewMap);
		}
	}
}

public class RelatedObjHandler
{
	// replace Opportunity__c, checkboxfld__c with actual API names

	
	public void onBeforeInsert(List<RelatedObj__c> lstNewRelatedObj)
	{
		Set<Id> setOppId = new Set<Id>();
		for(RelatedObj__c objRelatedObj : lstNewRelatedObj)
		{
			objRelatedObj.checkboxfld__c = true;
		}
	}
	
	public void onAfterInsert(Map<Id,RelatedObj__c> mapNewRelatedObj)
	{
		Set<Id> setOppId = new Set<Id>();
		List<RelatedObj__c> lstRelatedObjToUpdate = new List<RelatedObj__c>();
		for(RelatedObj__c objRelatedObj : mapNewRelatedObj.values())
		{
			
			if(objRelatedObj.Opportunity__c != NULL)
				setOppId.add(objRelatedObj.Opportunity__c);
		}
		
		// fetch old related obj records of parent opportunity and set checkbox to false
		for(RelatedObj__c objRelatedObj : [SELECT Id, checkboxfld__c 
											FROM RelatedObj__c
											WHERE Id NOT IN : mapNewRelatedObj.keySet()
											AND Opportunity__c IN: setOppId])
		{
			objRelatedObj.checkboxfld__c = false;
			lstRelatedObjToUpdate.add(objRelatedObj);
		}
		
		if(!lstRelatedObjToUpdate.isEmpty())
			update lstRelatedObjToUpdate;
	}
}

 
This was selected as the best answer
Rogerio Lara 2028Rogerio Lara 2028
Hi Nayana, thank you for coming to the rescue! Really appreciate.

Okay. The object is Opportunity Positioning. So I am getting the following error message: 

Error: Compile Error: Invalid type: OpportunityPositioningHandler at line 3 column 52


trigger OpportunityPositioningTrigger on Opportunity_Positioning__c(before insert, after insert)
{
    OpportunityPositioningHandler objHandler = new OpportunityPositioningHandler();

    if(trigger.isBefore)
    {
        if(Trigger.isInsert)
        {
            objHandler.onBeforeInsert(Trigger.New);
        }
    }
    if(trigger.isAfter)
    {
        if(Trigger.isInsert)
        {
            objHandler.onAfterInsert(Trigger.NewMap);
        }
    }
}
Nayana KNayana K
FIrst create OpportunityPositioningHandler class and then trigger code
Rogerio Lara 2028Rogerio Lara 2028
Of course. Silly me. Okay. I have done that. Now, I will create the trigger. ;-) 
 
Rogerio Lara 2028Rogerio Lara 2028
Nayana, you are simply a Super STAR! I don't know how to thank you enough. I've been struggling with this for the last 2 days. Thank you so so much!
rog
 
Nayana KNayana K
Glad to know it worked :) Cheers ;) Happy coding
Rogerio Lara 2028Rogerio Lara 2028
Hi Nayana,

Hope you're well. 

Sorry to bother, but I was wondering if you could assist further with the above.

The trigger and class are working as expected in the sandbox, but I unfortunately I am having difficulties to push them into production. 

Apparently I need a test class to run test first as there is 0% coverage. 

Thank you,

rog



 
Rogerio Lara 2028Rogerio Lara 2028
Thank you so much Nayana. I owe another one! Really appreciate! ;-) The trigger is: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 trigger OpportunityPositioningTrigger on Opportunity_Positioning__c(before insert, after insert) { OpportunityPositioningHandler objHandler = new OpportunityPositioningHandler(); if(trigger.isBefore) { if(Trigger.isInsert) { objHandler.onBeforeInsert(Trigger.New); } } if(trigger.isAfter) { if(Trigger.isInsert) { objHandler.onAfterInsert(Trigger.NewMap); } } } And the Apex class is: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 public class OpportunityPositioningHandler { // replace Opportunity__c, Most_current_position__c with actual API names public void onBeforeInsert(List lstNewOpportunityPositioning) { Set setOppId = new Set(); for(Opportunity_Positioning__c objOpportunityPositioning : lstNewOpportunityPositioning) { objOpportunityPositioning.Most_current_position__c = true; } } public void onAfterInsert(Map mapNewOpportunityPositioning) { Set setOppId = new Set(); List lstOpportunityPositioningToUpdate = new List(); for(Opportunity_Positioning__c objOpportunityPositioning : mapNewOpportunityPositioning.values()) { if(objOpportunityPositioning.Opportunity__c != NULL) setOppId.add(objOpportunityPositioning.Opportunity__c); } // fetch old related obj records of parent opportunity and set checkbox to false for(Opportunity_Positioning__c objOpportunityPositioning : [SELECT Id, Most_current_position__c FROM Opportunity_Positioning__c WHERE Id NOT IN : mapNewOpportunityPositioning.keySet() AND Opportunity__c IN: setOppId]) { objOpportunityPositioning.Most_current_position__c = false; lstOpportunityPositioningToUpdate.add(objOpportunityPositioning); } if(!lstOpportunityPositioningToUpdate.isEmpty()) update lstOpportunityPositioningToUpdate; } }
Nayana KNayana K
@isTest
public class OpportunityPositioningHandlerTest
{
	// replace Opportunity__c, checkboxfld__c with actual API names

	static testMethod void testForOnlyOneCheckboxSet() 
	{
		Opportunity objOpp = new Opportunity(Name = 'Test Opp', StageName = 'Prospecting', CloseDate = Date.Today()+2);
		insert objOpp;
		
		// assuming name is not auto number here
		Opportunity_Positioning__c objOppPos1 = new Opportunity_Positioning__c(Name = 'Test Pos1',Opportunity__c = objOpp.Id, /*ADD REST OF THE REQUIRED FIELD-VALUE PAIRS IF ANY*/);
		insert objOppPos1;
		
		// verify if newly inserted Opportunity Positioning is having checkboxfld__c = true
		system.assertEquals(true, [SELECT checkboxfld__c FROM Opportunity_Positioning__c WHERE Id =: objOppPos1.Id].checkboxfld__c);
		
		// insert one more Opportunity Positioning
		Opportunity_Positioning__c objOppPos2 = new Opportunity_Positioning__c(Name = 'Test Pos2',Opportunity__c = objOpp.Id,/*ADD REST OF THE REQUIRED FIELD-VALUE PAIRS IF ANY*/);
		insert objOppPos2;
		
		// verify if recent Opportunity Positioning's checkboxfld__c = true
		system.assertEquals(false, [SELECT checkboxfld__c FROM Opportunity_Positioning__c WHERE Id =: objOppPos1.Id].checkboxfld__c);
		system.assertEquals(true, [SELECT checkboxfld__c FROM Opportunity_Positioning__c WHERE Id =: objOppPos2.Id].checkboxfld__c);
		
	}
	
}

 
Rogerio Lara 2028Rogerio Lara 2028
Hi Nayana, thank you very much for this. I have added the test and updated with the relevant field, but unfortunately the test failing. Any idea of what I am not doing right?

@isTest
public class OpportunityPositioningHandlerTest
{
    // replace Opportunity__c, checkboxfld__c with actual API names

    static testMethod void testForOnlyOneCheckboxSet() 
    {
        Opportunity objOpp = new Opportunity(Name = 'Test Opp', StageName = 'Prospecting', CloseDate = Date.Today()+2);
        insert objOpp;
        
        // assuming name is not auto number here
        Opportunity_Positioning__c objOppPos1 = new Opportunity_Positioning__c(Name = 'Test Pos1',Opportunity__c = objOpp.Id);
        insert objOppPos1;
        
        // verify if newly inserted Opportunity Positioning is having checkboxfld__c = true
        system.assertEquals(true, [SELECT Most_current_position__c FROM Opportunity_Positioning__c WHERE Id =: objOppPos1.Id].Most_current_position__c);
        
        // insert one more Opportunity Positioning
        Opportunity_Positioning__c objOppPos2 = new Opportunity_Positioning__c(Name = 'Test Pos2',Opportunity__c = objOpp.Id);
        insert objOppPos2;
        
        // verify if recent Opportunity Positioning's checkboxfld__c = true
        system.assertEquals(false, [SELECT Most_current_position__c FROM Opportunity_Positioning__c WHERE Id =: objOppPos1.Id].Most_current_position__c);
        system.assertEquals(true, [SELECT Most_current_position__c FROM Opportunity_Positioning__c WHERE Id =: objOppPos2.Id].Most_current_position__c);
        
    }
    
}
Nayana KNayana K
Can you please let me know what the error says?
Rogerio Lara 2028Rogerio Lara 2028
System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [ProjectStartDate__c]: [ProjectStartDate__c]
Rogerio Lara 2028Rogerio Lara 2028

Hi Nayana,
Test passed now. I have removed the required field. Thank you ever so much.!
Rog
Nayana KNayana K
Great :) Happy Coding Rog :)
Rogerio Lara 2028Rogerio Lara 2028
Hi Nayana,

How are you doing?
I was wondering if you could save once again please ;-)

I have the following trigger and a validation rule that helps to enforce contact roles to be created for the opportunities depending on the sales stage and amount of the opportunity. This is working well.

------------------------------------------------------------------------------------------ This is what I have - FYI ---------------------------------------------------------------------------------

trigger updatecontactrolecount on Opportunity (before insert, before update)
{

Boolean isPrimary;
Integer iCount;

Map<String, Opportunity> oppty_con = new Map<String, Opportunity>();//check if the contact role is needed and add it to the oppty_con map
for (Integer i = 0; i < Trigger.new.size(); i++) 
{
        oppty_con.put(Trigger.new[i].id,
        Trigger.new[i]);      
}
isPrimary = False; 
for (List<OpportunityContactRole> oppcntctrle :[select OpportunityId from OpportunityContactRole where (OpportunityContactRole.IsPrimary = True and OpportunityContactRole.OpportunityId in :oppty_con.keySet())])
{
 if (oppcntctrle .Size() >0)
 {
 isPrimary = True;     
 }
}
iCount = 0;
for (List<OpportunityContactRole> oppcntctrle2 : [select OpportunityId from OpportunityContactRole where (OpportunityContactRole.OpportunityId in :oppty_con.keySet())])//Query for Contact Roles
{    
 if (oppcntctrle2 .Size()>0)
 {
 iCount= oppcntctrle2 .Size();     
 }
}
for (Opportunity Oppty : system.trigger.new) //Check if  roles exist in the map or contact role isn't required 
{
Oppty.Number_of_Contacts_Roles_Assigned__c = iCount;
Oppty.Primary_Contact_Assigned__c =isPrimary; 
}
}

Validation rule: 
AND(OR(ISPICKVAL(StageName, 'Advanced Proposal'), ISPICKVAL (StageName, 'Final Negotiation'), ISPICKVAL (StageName, 'Contract Signed')),  Number_of_Contacts_Roles_Assigned__c <2,  Amount  >= 1000000)

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Now this is what I need:

Standard Object = Opportunity
Custom Object = Strategic Client Opportunity Plan

I created a read only checkbox field on the opportunity = Has_Strategic_Client_Opportunity_Plan__c and left it unchecked

I want the trigger to check the "Has_Strategic_Client_Opportunity_Plan__c" when a new Strategic Client Opportunity Plan is created. 

Then I will create a validation rule on the opportunity to check whether this field is checked and the other required values too.

Does this make sense?

Your help is really appreciated. ;-)

Thank you,

Rog