Cross Object Field(Picklist) Update - triggers

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;
}

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);
}
}
}

How to merge two leads using an apex Trigger

I'm new to salesforce and I'm trying to learn more. Currently I'm stuck at a point where I don't know what to do further. Kindly point me in the right direction. Any help is appreciated.
So what im trying to do is to compare lastnames to find duplicates when the record is being created and if a duplicate is found then instead of creating it as a new record it should be merged with existing record.
So to achieve the task I have wrote the following trigger handler:
public class LeadTriggerHandler {
public static void duplicateMerge(){
List<Lead> leadList = [SELECT Id,Name, Email, Phone, FirstName, LastName FROM Lead];
List<Lead> leadTrigger = Trigger.new;
for(Lead leadVarTrigger : leadTrigger){
for(Lead leadVar : leadList){
//System.debug(leadVar.LastName + '==' + leadVarTrigger.LastName);
if(leadVarTrigger.LastName == leadVar.LastName)
{
//System.debug(leadVar.LastName + '==' + leadVarTrigger.LastName);
//leadVarTrigger.addError('This is a duplicate record');
Database.merge(leadVar, leadVarTrigger);
System.debug('Trigger Successful');
}
}
}
}
}
the following is my trigger:
trigger LeadTrigger on Lead (after insert) {
if(Trigger.isafter && Trigger.isInsert)
{
LeadTriggerHandler.duplicateMerge();
}
}
And when I try with after insert i get the following error:
LeadTrigger: execution of AfterInsert caused by: System.DmlException: Merge failed. First exception on row 0 with id 00Q5j00000ENUGVEA5; first error: INVALID_FIELD_FOR_INSERT_UPDATE, Unable to create/update fields: Name. Please check the security settings of this field and verify that it is read/write for your profile or permission set.: [Name] Class.LeadTriggerHandler.duplicateMerge: line 18, column 1 Trigger.LeadTrigger: line 5, column 1
And if i try with before trigger i get the following error for the same code:
LeadTrigger: execution of BeforeInsert caused by: System.StringException: Invalid id at index 0: null External entry point Trigger.LeadTrigger: line 5, column 1
Actually, according to your code, you are allowing the record to be created and saved to the database by using after insert. Your before insert failed because your handler class is referencing an Id, however, if you use before logic, the record isn't saved to the database yet, meaning it doesn't have an Id. With that being said, let's try the following. :)
The Trigger (Best practice is to have one trigger with all events):
trigger TestTrigger on Lead (before insert, before update, before delete, after insert, after update, after delete, after undelete) {
if(Trigger.isafter && Trigger.isInsert)
{
//Can't conduct DML operations with trigger.new or trigger.old
//So we will create a set and send this to our handler class
Set<Id> leadIds = Trigger.newMap.keySet();
LeadTriggerHandler.duplicateMerge(leadIds);
}
}
The Handler Class:
public class LeadTriggerHandler {
public static void duplicateMerge(Set<Id> idsFromTrigger){
//Querying the database for the records created during the trigger
List<Lead> leadTrigger = [SELECT Id, LastName FROM Lead WHERE Id IN: idsFromTrigger];
List<String> lastNames = new List<String>();
//This set is important as it prevents duplicates in our dml call later on
Set<Lead> deDupedLeads = new Set<Lead>();
List<Lead> leadsToDelete = new List<Lead>();
for (Lead l : leadTrigger){
//getting all of the Last Names of the records from the trigger
lastNames.add(l.lastName);
}
//We are querying the database for records that have the same last name as
//the records that were created during our trigger
List<Lead> leadList = [SELECT Id, Name, Email, Phone, FirstName, LastName FROM Lead WHERE LastName IN: lastNames];
for(Lead leadInTrigger : leadTrigger){
for(Lead leadInList : leadList){
if(leadInTrigger.LastName == leadInList.LastName){
//if the lead from the trigger has the same last name as a lead that
//already exists, add it to our set
deDupedLeads.add(leadInTrigger);
}
}
}
//add all duplicate leads from our set to our list and delete them
leadsToDelete.addAll(deDupedLeads);
delete leadsToDelete;
}
}
This handler has been bulkified in two ways, we removed the DML operation out of the loop and the code is able to process a scenario where someone mass inserts 1000s of leads at a time. Plus, rather than querying every lead record in your database, we only query for records that have the same last name as the records created during the insert operation. We advise using something more unique than LastName like Email or Phone as many people/leads can have the same Last Name. Hope this helps and have a blessed one.

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.

Salesforce Trigger: Update field Trigger from Custom Object

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;
}
}
}

Change Lead owner trigger before insert

I have a trigger change owner before insert a new lead record.
trigger trickOnLead on Lead (before insert) {
for (Lead ld : Trigger.new) {
if(ld.testId__c != null ){
ld.ownerid = ld.testId__c;
}
}
}
I tested it through web-to-lead, and its successful.(on Monday, July 8th),
but today its not work anymore ?!
note that it only work for manual create a new record.
Thanks,
Manh
trigger trickOnLead on Lead (before insert, before update) {
for (Lead ld : Trigger.new) {
if(ld.testId__c != null ){
ld.ownerid = ld.testId__c;
}
}
}