Salesforce Trigger: Update field Trigger from Custom Object - triggers

New to apex and have a question about writing triggers. Essentially, I'm trying to create a trigger that updates a given field when another field is updated (after a record is created/inserted into Salesforce).
More specifically, when a custom Account lookup field (lookup value is a custom object record) is updated, it should update another field with a different value from the custom object record.
i.e. When I update the High School name to Elm High School, it will also update the yield associated with that high school.
Below is the code that I've created so far:
trigger UpdateYield on Account (before update) {
Set<String> HS = new Set<String>();
for (Account hsName : Trigger.new) {
if (hsName.High_School_LU__c != null) {
HS.add(hsName.High_School_LU__c);
}
List<High_School__c> y = [SELECT Name, Yield__c FROM High_School__c WHERE Name IN :HS];
Map<String, High_School__c> yLU = new Map<String, High_School__c>();
for (High_School__c h : y) {
yLU.put(h.Name, h);
}
for (Account YieldU : Trigger.new) {
if (YieldU.High_School_LU__c != null) {
High_School__c a = yLU.get(YieldU.Name);
if (a != null) {
YieldU.Yield__c = a.Yield__c;
}
}
}
}
}
It saves however, it still does not work when I update the field.
Any help would be greatly appreciated. Thanks in advance.

The problem here is that the value of a lookup field is not actually a string (as displayed in the UI) but an ID, so when you perform your SOQL query you are comparing an ID to the Name field and getting no results.
If you change your code to the following you should get the result you expect.
It should also be notified that this simple use case could also be accomplished using a simple Workflow Field Update rather than a trigger.
trigger UpdateYield on Account (before update)
{
Set<Id> HS = new Set<Id>();
for (Account hsName : Trigger.new)
{
if (hsName.High_School_LU__c != null)
{
HS.add(hsName.High_School_LU__c);
}
}
Map<Id, High_School__c> y = [SELECT Name, Yield__c FROM High_School__c WHERE Id IN :HS];
for (Account YieldU : Trigger.new)
{
High_School__c a = y.get(YieldU.High_School_LU__c);
if (a != null)
{
YieldU.Yield__c = a.Yield__c;
}
}
}

Related

Trigger to auto populate field values

I have Custom object named Team__c and Fields are like, Category__c(Picklist), Close_Date__c(Date), Stage__c(Picklist) also have Standard Opportunity object. The Team__c object and Opportunity has look-up relationship with Category__c(Picklist), Close_Date__c(Date), Stage__c(Picklist) fields . In opportunity I have custom field named Type__c(Picklist), whenever the Type__c from Opportunity is equal to 'New Team' (Type__c == 'New Team') the Category__c, Close_Date__c, Stage__c fields should populate in Team__c record while it create.
Can anyone help on this?
Thanks in advance.
I have try with following trigger,
if(trigger.isAfter && trigger.isInsert)
{
List<Team__c> tt = new List<Team__c>();
Opportunity opp = new Opportunity();
if(opp.Type__c == 'New Team')
{
for(Opportunity oppty : trigger.new)
{
Team__c team = new Team__c();
team.Category__c = oppty.Category__c;
team.Close_Date__c = oppty.Close_Date__c;
team.Stage__c = oppty.Stage__c;
tt.add(team);
}
}
}

APEX Trigger update picklist on child object

I am trying to do something simple (I hope).
I have 2x objects: Contact and Career_Path__c
Contact has one field: Currency__c (picklist)
Career_Path__c has one field: Next_Currency__c (picklist)
hese two objects are related via a loopup relationship from Career_Path__c up to Contact
I am trying to update the Next_Currency__c field every time a new Career_Path__c record is created. This does not seem to work. Thanks for any suggestions.
trigger Trigger_dynPicklist_2 on Contact (after insert) {
Map<Id, String> contactIdToCareerPathMap = new Map<Id, String>();
for (Contact c : Trigger.new) {
if (String.isNotBlank(c.Id)) {
//System.debug('El contacto tiene id: '+c.Id);
contactIdToCareerPathMap.put(c.Id, c.Currency__c);
}
}
List<Career_Path__c> careerPathToUpdate = [SELECT Id, Next_Currency__c, Contact__c
FROM Career_Path__c
WHERE Contact__c IN :contactIdToCareerPathMap.keySet()
];
if(careerPathToUpdate.size() > 0){
//System.debug('Tiene hijos');
for (Career_Path__c career : careerPathToUpdate) {
//System.debug('hijos: '+ career.id);
career.Next_Currency__c = contactIdToCareerPathMap.get(career.Contact__c);
}
update careerPathToUpdate;
}
}
You're trying to set trigger on Contact when you actually need to set it on Career_Path__c SObject. Your code should look something like this to achieve Next_Currency__c auto-populated from related Contact Currency__c (also take a note that trigger will now be BEFORE insert, so you do not need to update record again):
trigger Trigger_dynPicklist_2 on Career_Path__c (before insert) {
Set<Id> relatedContactsIds = new Set<Id>();
for (Career_Path__c path : Trigger.new) {
if (path.Contact__c != null) {
relatedContactsIds.add(path.Contact__c);
}
}
Map<Id, Contact> relatedContactsMap = [SELECT Id, Currency__c FROM Contact WHERE Id IN :relatedContactsIds AND Currency__c != NULL];
for (Career_Path__c path : Trigger.new) {
if (path.Contact__c != null && relatedContactsMap.containsKey(path.Contact__c)) {
path.Next_Currency__c = relatedContactsMap.get(path.Contact__c).Currency__c;
}
}
}
Also note, that when Contact is just created (and you are in trigger on insert), it cannot have related Career_Path__c objects.

Access Trigger.New value in Apex Test Class

tl;dr - How do you make a test class wait until a specific trigger is done with its updates or inserts before continuing on with the test?
Background
I have a trigger that creates a new Portal_Content__c object whenever an Account object is created, and then associates both records with each other (see Account Trigger below).
I have also created a trigger on the Portal_Content__c object that fires when a record is deleted. When deleted, the trigger looks up the related Account record and deletes it (see Portal Content Trigger below).
My question is regarding my Portal Content Test Class (final code block below). When I run a DML insert on an Account record, the Account Trigger should populate the a.Portal_Content_Record__c field with the Portal Content record created in the Account Trigger. However, when I ran my system.debug() tests, it showed that the a.Portal_Content_Record__c field is null when the SOQL query is run. I have been able to bypass this by doing a search for the Portal Content record by matching name, but I would like to make the script more robust by searching by the exact ID.
Question
How do I make the Portal Content Test Class wait until the Account Trigger has populated the a.Portal_Content_Record__c field before moving on with the test?
--Code Blocks--
Account Trigger
trigger AccountHandler on Account (before insert, after insert, after update, after delete) {
List<Account> alist = Trigger.New;
List<Account> oldlist = Trigger.Old;
// Create new Portal Content with same name as Account if Account is record type 'College/University,'
// then assign newly created Portal Content to 'Portal Content Record' lookup field on new Account
if(Trigger.isBefore && Trigger.isInsert){
for(Account a : alist) {
if (a.RecordTypeId == '012i0000001Iy1H') {
Portal_Content__c p = new Portal_Content__c(
Name=a.Name,
RecordTypeId='012i0000001J1zZ'
);
insert p;
a.Portal_Content_Record__c = p.Id;
}
}
}
// Delete Portal Content record referenced in an Account's 'Portal Content Record' lookup field
// if the Account is deleted
if (Trigger.isAfter && Trigger.isDelete){
for(Account a : oldlist){
for(Portal_Content__c p : [SELECT ID FROM Portal_Content__c WHERE ID = :a.Portal_Content_Record__c]){
delete p;
}
}
}
// After the new Portal Content record has been created, assign the Account ID of the Account that created it
// to the 'School SFDC ID' field on the new Portal Content record.
if (Trigger.isAfter && Trigger.isInsert){
for(Account a : alist){
List<Portal_Content__c> plist = [SELECT ID FROM Portal_Content__c WHERE Id = :a.Portal_Content_Record__c];
for(Portal_Content__c p : plist){
p.School_SFDC_ID__c = a.Id;
update p;
}
}
}
// Prevent more than one Account from being assigned to a single Portal Content record
if (Trigger.isAfter && Trigger.isUpdate) {
for(Account a : alist){
if (a.Portal_Content_Record__c != null){
List<Account> alist = [SELECT ID FROM Account WHERE Portal_Content_Record__c = :a.Portal_Content_Record__c];
system.debug('alist: ' + alist);
if (alist.size() > 1) {
a.addError('The Portal Content record you selected is already associated with another School. Please select a different Portal Content record');
}
}
}
}
}
Portal Content Trigger
trigger PortalContentHandler on Portal_Content__c (before insert, after update, after insert, after delete) {
// If Portal Content is deleted and Account is tied to Account record, delete Account record
if(Trigger.isAfter && Trigger.isDelete){
List<Portal_Content__c> plist = Trigger.old;
for(Portal_Content__c p : plist) {
List<Account> alist = [SELECT ID FROM Account WHERE Id = :p.School_SFDC_ID__c];
for(Account a : alist){
delete a;
}
}
}
// If more than one Portal Content with the same name, prevent new Portal Content record from being created
else if(Trigger.isAfter && (Trigger.isUpdate || Trigger.isInsert)){
List<Portal_Content__c> plist = Trigger.New;
for(Portal_Content__c p : plist){
List<Portal_Content__c> pquery = [SELECT ID FROM Portal_Content__c WHERE Name = :p.Name];
if(pquery.size() > 1){
p.addError('There is already a Portal Content record with this name. Please select a different name.');
}
}
}
}
Portal Content Test Class
#isTest
public class PortalContentHandlerTest {
#isTest static void createThenDeletePortalContent(){
Account a = new Account(Name='deletePortalTest',RecordTypeId='012i0000001Iy1H');
insert a;
List<Portal_Content__c> plist = [SELECT ID FROM Portal_Content__c WHERE Name = :a.Name];//Id = :a.Portal_Content_Record__c];
system.debug('Delete Info: a.Id = ' + a.Id + ', Portal_Content_Record = ' + a.Portal_Content_Record__c+ ', plist = ' + plist);
for(Portal_Content__c p : plist){
delete p;
}
system.debug('Delete Info: a.Id = ' + a.Id);
List<Account> checklist = [SELECT ID FROM Account WHERE Id = :a.Id];
system.debug(checklist);
system.assertEquals(0, checklist.size());
}
I have tested it in my Org. Please find my comments below.
According to your requirement, I have a trigger that creates a new Portal_Content__c object whenever an Account object is created, and then associates both records with each other (see Account Trigger below).
I see there is a relationship on the Account(Portal_Content_Record__c ) and the Portal Content (School_SFDC_ID__c). You are setting the Portal_Content_Record__c. but you need to link the School_SFDC_ID__c as well to fulfill your requirement. Please find the below code
trigger AccountHandler on Account (before insert, after insert, after update, after delete) {
List<Account> alist = Trigger.New;
List<Account> oldlist = Trigger.Old;
// Create the new Portal Content with the same name as Account if Account is record type College/University,
// then assign newly created Portal Content to Portal Content Record lookup field on new Account
if(Trigger.isBefore && Trigger.isInsert){
for(Account a : alist) {
if (a.RecordTypeId == '012i0000001Iy1H') {
Portal_Content__c p = new Portal_Content__c(
Name=a.Name,
RecordTypeId='012i0000001J1zZ',
School_SFDC_ID__c = a.id
);
insert p;
a.Portal_Content_Record__c = p.Id;
}
}
}
}
I see the only thing is delete is not getting covered in
PortalContentHandler because it doesn't meet with the condition for
List<Account> alist = [SELECT ID FROM Account WHERE Id =
:p.School_SFDC_ID__c]; Populate it when you are creating
Portal Content as describe in the above point.
Also, you need to change your test class as there is no data for Portal Content that you are trying to query. In the test class, you get the data what you created there only. The one which gets created by AccountHandler won't be part of your test class. Create the same data as you are creating in the trigger.
#isTest
public class PortalContentHandlerTest {
#isTest static void createThenDeletePortalContent(){
Account a = new
Account(Name='deletePortalTest',RecordTypeId__c='012i0000001Iy1H');
insert a;
Portal_Content__c p = new Portal_Content__c(
Name=a.Name,
RecordTypeId__c='012i0000001J1zZ',
School_SFDC_ID__c = a.id
);
insert p;
delete p;
}
}

Prevent last contact from delete using trigger in salesforce

I am a newbie to salesforce and i have a requirement to which i need suggestions how to approach this requirement
I have 4 contacts related to one account and when someone deletes contacts, he should not be able to delete the last contact related to the account.For example: in account A1 i have 4 contacts and someone deletes the 3 contacts from that account then it should be deleted, after that there will be only 1 contact related to that account and den someone tries to delete the last contact than it should not be deleted.
How can i achieve this using trigger?
In your trigger, run a query for all contacts related to the account. If you are trying to delete all of them in this trigger, don't allow it. I don't know how you want to deal with people deleting multiple contacts at the same time, but let's say you will simply disallow the entire delete and the user has to retry with fewer contacts. If you want to come up with some logic that deletes all but 1 of the contacts, that's up to you.
Something like:
Trigger OnContactDelete on Contact (before delete) {
Set<ID> accountIds = new Set<ID>(); //all accounts that contacts are being deleted from
for (Contact contact : Trigger.old) {
accountIds.add(contact.AccountId);
}
List<Contact> contacts = [SELECT Id, AccountId FROM Contact WHERE AccountId IN :accountIds]; //get all of the contacts for all of the affected accounts
Map<ID, Set<ID>> deleteMap = new Map<ID, Set<ID>>(); //map an account ID to a set of contact IDs being deleted
Map<ID, Set<ID>> foundMap = new Map<ID, Set<ID>>(); //map an account ID to a set of contact IDs that were found by the query
for (Contact deleteContact : Trigger.old) {
Set<ID> idSet = deleteMap.get(deleteContact.AccountId);
if (idSet == null) {
idSet = new Set<ID>();
}
idSet.add(deleteContact.Id);
deleteMap.put(deleteContact.AccountId, idSet);
}
for (Contact foundContact : contacts) {
Set<ID> idSet = foundMap.get(foundContact.AccountId);
if (idSet == null) {
idSet = new Set<ID>();
}
idSet.add(foundContact.Id);
foundMap.put(foundContact.AccountId, idSet);
}
for (ID accountId : accountIds) { //go through each affected account
Set<ID> deleteIds = deleteMap.get(accountId);
Set<ID> foundIds = foundMap.get(accountId);
if (deleteIds != null && foundIds != null && deleteIds.containsAll(foundIds)) {
for (Contact contact : Trigger.old) {
if (deleteIds.contains(contact.Id)) { //this is one of the contacts being deleted
contact.addError('This contact is potentially the last contact for its account and cannot be deleted');
}
}
}
}
}
Note, I just typed this up in SO and haven't actually tested the code at all, even for syntax errors like missing semicolons or braces. It should work in theory, but there may be better ways of doing it.
You can solve this without triggers. You can create a Roll-Up Summary field on Account that counts the Contact records (ContactCount__c) and evaluate this count in a validation Rule on Account like this:
ContactCount__c = 0 && PRIORVALUE(ContactCount__c) > 0

Cross Object Field(Picklist) Update

Can anyone help me with writing a trigger on cross object field update.
Object: Booking__c Field: Booking_Type__c (is a picklist)
Object: Booking_Item__C Field: Booking_type__c (is also a picklist)
The requirement is, when status (Booking_Type_c) of Booking_c is selected as cancelled the status (Booking_Type__c ) of Booking_item__c should also be updated to cancelled.
Any help will be much appreciated.
Thank you
I'd like to make an assumption that your objects have the following relationship
Booking_item__c.Booking__c (Booking_item_c record has a lookup to Booking_c)
Trigger Booking on Booking__c (after insert, after update) {
Set<Id> cancelledBookingIds = new Set<Id>();
for (Booking__c booking: Trigger.new) {
if (booking.Booking_Type__c == 'cancelled') {
cancelledBookingIds.add(booking.id);
}
}
List<Booking_Item__c> bookingItemsForCancelling = [SELECT Booking_Type__c
FROM Booking_Item__c
WHERE Booking__c IN: cancelledBookingIds];
for (Booking_Item__c item: bookingItemsForCancelling) {
item.Booking_Type__c = 'cancelled';
}
update bookingItemsForCancelling;
}