I am new to apex and I have created an apex trigger that will create new residents whenever a city census(custom object) is approved. The created residents is based on the contacts object's details which are only a few fields and the resident record will depend on the salutation of the contact object (mr for male record type and ms for female record type).
There is also a master-detail relationship in the resident object, it is a lookup for the city census record. I am wondering if it is possible to get the specific id of that city census record and assign it to its child record which is the resident.
Here is the code:
trigger ResidentTrigger on City_Census__c (After update, Before insert) {
List<Resident__c> residentData = new List<Resident__c>();
Id maleRecordTypeId = Schema.SObjectType.Resident__c.getRecordTypeInfosByName().get('Male Resident').getRecordTypeId();
Id femaleRecordTypeId = Schema.SObjectType.Resident__c.getRecordTypeInfosByName().get('Female Resident').getRecordTypeId();
for(City_Census__c cityCensus: Trigger.new) {
Resident__c newResident = new Resident__c();
for(Contact con : [SELECT Id, Name, FirstName, LastName, City__c, Salutation FROM Contact WHERE City__c != NULL]) {
if(cityCensus.Approval_Status__c == 'Approved') {
if(cityCensus.City__c == con.City__c) {
if(con.Salutation == 'Mr.' || con.Salutation == 'Mr') {
newResident.Name = con.Name;
newResident.First_Name__c = con.FirstName;
newResident.Last_Name__c = con.LastName;
newResident.City__c = con.City__c;
newResident.City_Census__c = cityCensus.Id; //Lookup, master-detail relationship
newResident.RecordTypeId = maleRecordTypeId;
}
else if(con.Salutation == 'Ms.' || con.Salutation == 'Ms') {
newResident.Name = con.Name;
newResident.First_Name__c = con.FirstName;
newResident.Last_Name__c = con.LastName;
newResident.City__c = con.City__c;
newResident.City_Census__c = cityCensus.Id; //Lookup, master-detail relationship
newResident.RecordTypeId = femaleRecordTypeId;
}
system.debug(newResident.Name);
system.debug(newResident.First_Name__c);
system.debug(newResident.Last_Name__c);
system.debug(newResident.City__c);
system.debug(newResident.RecordTypeId);
system.debug(newResident.City_Census__c);
}
}
}
insert residentData;
}
}