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
NarcissuNarcissu 

Put the case open date in Case Object to a custom field in Account Object

Hi,

 

I am a new user to Apex.

 

I am trying to write a trigger which will automatically enter the case open date to a custom date field on my Account object when anyone in my group opens a case for the client.

 

I understand the difficulty is to sync records between two objects. In both objects, I have a field called Account Name. My guess is to figure out a way to match this field in both objects and then write down a code to insert the case open date to the custom field.

 

I also copied and tried to modify the code from other users to fit my own situation, however I may get into a wrong direction. Following is the code I copied, I put it in the case object:

 

trigger Caseupdate on Case(after insert) {
Case b = new Case();
Set<Date> AccountIDs = new set<Date>();
map<Date, Account> AcctMap = new Map<Date, Account>();
for(Account c : Trigger.new){
AccountIDs.add(c.CreatedDate);
}
for(Account at:[Select a.CreatedDate
From Account a where a.CreatedDate = 'Date/Time Opened']){
AcctMap.put(at.CreatedDate, at);
}
for(Account c: Trigger.new){
if(AcctMap.contains(c.CreatedDate)){
c.Last_Update = AcctMap.get(c.CreatedDate);
}
}
}

 

Thanks in advance, any helps are much appreciated.

Best Answer chosen by Admin (Salesforce Developers) 
Navatar_DbSupNavatar_DbSup

Hi,


Try the below code as reference:
trigger Caseupdate on Case(after insert)
{
Case b = new Case();
Set<id> AccountIDs = new set<id>();
list<Account> AcctList = new list<Account>();
for(case c : Trigger.new)
{
for(Account at:[Select id,customCreatedDate__c From Account where id =: c.accountid])
{
at.customCreatedDate__c = date.valueof(c.createddate);
AcctList.add(at);
}
}
update AcctList;
}

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved. 

All Answers

Navatar_DbSupNavatar_DbSup

Hi,


Try the below code as reference:
trigger Caseupdate on Case(after insert)
{
Case b = new Case();
Set<id> AccountIDs = new set<id>();
list<Account> AcctList = new list<Account>();
for(case c : Trigger.new)
{
for(Account at:[Select id,customCreatedDate__c From Account where id =: c.accountid])
{
at.customCreatedDate__c = date.valueof(c.createddate);
AcctList.add(at);
}
}
update AcctList;
}

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved. 

This was selected as the best answer
NarcissuNarcissu

Thanks so much! That is exactly what I need.

 

By the way, if I enter another new case for the same account someday later, will the code also update the date?

ashish raiashish rai

Hi,

Yes it will update that field with new value.