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
velgoti rani 18velgoti rani 18 

check for existance of case related to custom object

Hi Team,

I have scenario where there is custom Object (A) and Standard Object (Cases). we are showing cases as related list on Custom object (A). My Question is i want to have only one case of particular record type to be created for that custom object.  We have a button on Custom Object ( A) page layout to create case with particular record type. If we have already a case of that record type existing under cases with status Inprogress , then create the case and change the status to "closed". Can anyone suggest m,e best approach for this???
jigarshahjigarshah
Here are a few approaches you cna take.

1. If your button on Custom Object A is a button that executes Javascript, you can update the Javscript code on that button to check for an existing Case and close it and then create a new Case record.

2. If your button on Custom Object A is a button that redirects to a Visualforce page (Check the url within the address bar of your web browser to see if its format is https://c.you_instance.salesforce.com/apex/page_name), you can perform the check for an existing Case with the same record type by calling the respective Apex method containing the logic within the action attribute of the <apex:page> tag as shown below.

Visualforce Page
<apex:page action="{!closeCase}">

  //Your other Visualforce code

</apex:page>
Apex Controller containing the method
public with sharing class CaseManager{

	//Constructor
	public CaseManager(){}

	public PageReference closeCase(){
	
		//Logic to check for existing Case of a record type and close it goes here
	}
}

3. You can use an Apex trigger written on after insert and after update of Case A which checks for any existing In Progress Case records associated with the same Custom Object A, and closes them whenever a new Case record is created.
trigger CaseTrigger on Case(after insert){

	if(Trigger.isAfter){
	
		if(Trigger.isInsert){
		
			new CaseManager().closeCase();
		}
	}//isAfter
}

4. You could also use a Validation Rule to restrict the creation of an exsting Case record if a Case already exists. You can check for existing Cases using a Rollup Summary COUNT() field which counts the Case records matching a specifc condition. I believ you may not be able to use this because you might be using a lookup relationship here.

Please mark the thread as SOLVED and answer as the BEST ANSWER if it helps address your issue.