Update Parent Object Field in Apex Trigger - salesforce

I have three objects
1)Truck__c
2)Booking__C
3)Payment___C.
Truck and Booking has master detail relationship where Truckk is master and Booking is detail.
Booking and payment has lookup relationship where Booking is parent and payment is child.
I want to update a field present isBooked(checkbox) in Truck based on the value present in a field remainingAmount in payment object. I have added trigger on Payment object like below
trigger TestTrigger on Payment__c (after insert) {
if(Trigger.isAfter && Trigger.isUpdate){
for (Payment__c pay:Trigger.New)
{
payId.add(pay.id);
paidAmount =Integer.valueOf(pay.Paid_Amount__c);
}
Map <id,Booking__c> bookingMap = new Map <id,Booking__c> ();
for (Booking__c obj: [Select Id, Booking_ID__c from Booking__c where Booking_ID__c in:payId])
{
bookingMap.put(obj.Booking_ID__c, obj);
}
for(Booking__c objBooking:matchingIdsMap){
Truck__c truckObj = [Select id,Price__c from Truck__c where Truck__c.id = objBooking.Truck__c.id];
//Integer paidAmount = Payment__c.Paid_Amount__c;
Integer totalAmount = Integer.valueOf(truckObj.Price__c);
Integer remainingAmount = totalAmount-paidAmount;
If(remainingAmount == 0){
truckObj.Booked__c = true
}
update truckObj;
}
}
}
Here first I am getting payment ID's and based on that I am fetching Booking objects which is lookup parent of payment. After this I am trying to fetch the truck object which is master of Booking. But I don't know how to query on this as where clause in query giving error
Truck__c truckObj = [Select id,Price__c from Truck__c where Truck__c.id = objBooking.Truck__c.id];
Please note there is no direct relationship between Truck and Payment
How can I fetch truck object
Thanks in Advance

Short answer: while referring to parent fields, you should use the relationship name, so Truck__r instead of Truck__c.
Anyway it is not the only problem with that code.
Long answer:
your trigger is in after insert, but you check for an after update event: if(Trigger.isAfter && Trigger.isUpdate). Probably you want to run this trigger in both after insert and after update.
You never declared payId nor paidAmount which you use in your first for-loop. Anyway paidAmount would just hold the last value, which probably you won't need.
[Select Id, Booking_ID__c from Booking__c where Booking_ID__c in:payId] this query should return an empty list because in payId you've stored the ids of Payment__c, that is a child of Booking__c, while in the first loop you should have stored the ids of parents Booking__c
[Select id,Price__c from Truck__c where Truck__c.id = objBooking.Truck__c.id] Here there is no reason to write where Truck__c.id It should be just WHERE Id = :objBooking.Truck__c.
Beware: putting a SOQL in a loop you will easily hit the Governor Limit about SOQL, which will raise a System.LimitException: Too many SOQL queries: 101.
The same goes by putting a DML in a loop.
I'm going to assume that the API Name of the lookup fields is the same of the parent object, so that a Booking__c field exists on Payment__c object and a Truck__c exists on Booking__c object.
If I got the logic right about how setting the flag on Truck object, this should be the trigger code.
trigger TestTrigger on Payment__c (after insert, after update) {
if(Trigger.isAfter && (Trigger.isInsert || Trigger.isUpdate)) {
Map<Id, List<Payment__c>> mapBookingIdPaymentList = new Map<Id, List<Payment__c>>();
for (Payment__c pay : Trigger.New) {
List<Payment__c> paymentList = mapBookingIdPaymentList.get(pay.Booking__c);
if (paymentList == null) {
paymentList = new List<Payment__c>();
mapBookingIdPaymentList.put(pay.Booking__c, paymentList);
}
paymentList.add(pay);
}
Map<Id, Decimal> mapTruckPrice = new Map<Id, Decimal>();
Map<Id, Integer> mapTruckRemainingAmount = new Map<Id, Integer>();
for (Booking__c booking: [SELECT Id, Truck__c, Truck__r.Price__c FROM Booking__c WHERE Id IN :mapBookingIdPaymentList.keySet()]) {
mapTruckPrice.put(booking.Truck__c, booking.Truck__r.Price__c);
Integer sumOfRemainingAmount = mapTruckRemainingAmount.containsKey(booking.Truck__c) ? mapTruckRemainingAmount.get(booking.Truck__c) : 0;
for (Payment__c pay : mapBookingIdPaymentList.get(booking.Id)) {
sumOfRemainingAmount += pay.Paid_Amount__c != null ? pay.Paid_Amount__c.intValue() : 0;
}
mapTruckRemainingAmount.put(booking.Truck__c, sumOfRemainingAmount);
}
List<Truck__c> trucksToUpdate = new List<Truck__c>();
for (Id truckId : mapTruckPrice.keySet()) {
// There is no need to query a record just to update it if you already have its Id.
Truck__c truck = new Truck__c(Id = truckId);
truck.Booked__c = mapTruckPrice.get(truckId) - mapTruckRemainingAmount.get(truckId) == 0;
trucksToUpdate.add(truck);
}
update trucksToUpdate; // dml outside the loop
}
}
By the way, you should move the logic in an handler class, following the best practices.

Related

Salesforce assigning Service Territories to Assets based on coordinates

I want to assign service territories to Assets, based on a Geolocation field whihc containts two coordinates.
With my below attempt I keep getting the error: Error: Compile Error: Unexpected token ','. at line 14 column 163
I can't seem to find the actual error in my code.
My first thought that I did not have a Relationship between the Asset and the Map Polygon object, but there is a lookup relationship between them.
trigger AssetTerritoryAssignment on Asset (before insert, before update) {
// Create a list to store the Ids of the Assets that need to be updated
List<Id> assetIds = new List<Id>();
// Loop through the trigger records to collect the Ids of the Assets that need to be updated
for (Asset asset : Trigger.new) {
if (asset.gps_fix__c != null && asset.Polygon_Relationship__c != null) {
assetIds.add(asset.Id);
}
}
// Use a map to store the Ids of the territories that contain the Assets
Map<Id, Id> territoryIdMap = new Map<Id, Id>();
//Use a query to find the territories that contain the Assets
for(Asset a: [SELECT Id, gps_fix__c, Service_Territory__c, Polygon_Relationship__c FROM Asset WHERE Id IN :assetIds]) {
FSL__Polygon__c polygon = [SELECT Id FROM FSL__Polygon__c WHERE Id =: a.Polygon_Relationship__c AND ST_WITHIN(a.gps_fix__c, FSL__KML__c) = true limit 1];
if(polygon != null) {
territoryIdMap.put(a.Id, polygon.Id);
}
}
// Create a list of Assets to update
List<Asset> assetsToUpdate = new List<Asset>();
// loop through the assets and update their territory
for (Asset asset : [SELECT Id, Territory__c FROM Asset WHERE Id IN :assetIds]) {
if (territoryIdMap.containsKey(asset.Id)) {
asset.Territory__c = territoryIdMap.get(asset.Id);
assetsToUpdate.add(asset);
}
}
update assetsToUpdate;
}

What does the oldmap actually do here? Can someone explain

This is a code to create a new task when stage is inserted or updated to Closed Won
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {
List<Task> tl = new List<Task>();
for(Opportunity op : Trigger.new) {
if(Trigger.isInsert) {
if(Op.StageName == 'Closed Won') {
tl.add(new Task(Subject = 'Follow Up Test Task', WhatId = op.Id));
}
}
if(Trigger.isUpdate) {
if(Op.StageName == 'Closed Won'
&& Op.StageName != Trigger.oldMap.get(op.Id).StageName) {
tl.add(new Task(Subject = 'Follow Up Test Task', WhatId = op.Id));
}
}
}
if(tl.size()>0) {
insert tl;
}
}
Here, what does && Op.StageName != Trigger.oldMap.get(op.Id).StageName) do? Why do we use oldMap here?
Trigger.newMap is the map of IDs of new object values. Available in insert, update, and undelete triggers, and 'new' records can only be modified in before triggers.
Trigger.oldMap is the map of IDs of old object values. Available in update and delete triggers only.
if (Trigger.isUpdate) {
// Iterate updated opportunities
for (Opportunity o : Trigger.new) {
// Get the opportunity before update
Opportunity oldOpp = Trigger.oldMap.get(o.Id);
// Check if a value changed
if (o.Some_Value__c == oldOpp.Some_Value__c) {
System.debug('Value did not change.');
} else {
System.debug('Value changed!');
}
}
}
Note: I could have used Trigger.newMap instead of Trigger.new but I'd be looping through Trigger.newMap.values() instead - with the same end result. newMap is just a convenient way of getting the bulkified data in map form instead of a list.
We use old map to compare with the new value of the Some_Value__c custom field. If the two values differ then the field value has changed. Of course, if you read the code in the two if branches, this is obvious.

Apex - Retrieving Records from a type of Map<SObject, List<SObject>>

I am using a lead map where the first id represents an Account ID and the List resembles a list of leads linked to that account such as: Map<id, List<Id> > leadMap = new Map< id, List<id> >();
My question stands as following: Knowing a Lead's Id how do I get the related Account's Id from the map. My code looks something like this, The problems is on the commented out line.
for (Lead l : leads){
Lead newLead = new Lead(id=l.id);
if (l.Company != null) {
// newLead.Account__c = leadMap.keySet().get(l.id);
leads_to_update.add(newLead);
}
}
You could put all lead id and mapping company id in the trigger then get the company id
Map<string,string> LeadAccountMapping = new Map<string,string>();//key is Lead id ,Company id
for(Lead l:trigger.new)
{
LeadAccountMapping.put(l.id,l.Company);
}
//put the code you want to get the company id
string companyid= LeadAccountMapping.get(l.id);
Let me make sure I understand your problem.
Currently you have a map that uses the Account ID as the key to a value of a List of Lead IDs - So the map is -> List. Correct?
Your goal is to go from Lead ID to the Account ID.
If this is correct, then you are in a bad way, because your current structure requires a very slow, iterative search. The correct code would look like this (replace your commented line with this code):
for( ID actID : leadMap.keySet() ) {
for( ID leadID : leadMap.get( actId ) ) {
if( newLead.id == leadID ) {
newLead.Account__c = actId;
leads_to_update.add(newLead);
break;
}
}
}
I don't like this solution because it requires iterating over a Map and then over each of the lists in each of the values. It is slow.
If this isn't bulkified code, you could do a Select Query and get the Account__c value from the existing Lead by doing:
newLead.Account__c = [ SELECT Account__c FROM Lead WHERE Id = :l.id LIMIT 1];
However, this relies on your code not looping over this line and hitting a governor limit.
Or you could re-write your code soe that your Map is actually:
Map<ID, List<Leads>> leadMap = Map<ID, List<Leads>>();
Then in your query where you build the map you ensure that your Lead also includes the Account__c field.
Any of these options should work, it all depends on how this code snippet in being executed and where.
Good luck!

Apex Trigger with custom objects

2 custom objects
1.Merchandise
2.invoice
whenever a new merchandise is created an auto invoice has to be created.As am new to apex,please bear with me.Any one please correct my code.
code:
trigger createinvoice on Merchandise2__c (after insert,after update) {
list<Invoice2__c>line = new list<Invoice2__c>();
for(Merchandise2__c mer:Trigger.new){
Invoice2__c li = new Invoice2__c();
line =[select id from Invoice2__c ];
li.name = mer.Name;
li.Status__c='open';
li.id = mer.id;
line.add(li);
}
insert line;
}
First remove the after update from your trigger unless you want a new invoice created each time someone updates the Merchandise record.
I'm not sure what you were trying to accomplish with the select line.
"line =[select id from Invoice__c];" this doesn't seem to accomplish anything. Also you're trying to set the id field of the invoice to the id of the merchandise record. You can't do that. You'll need a lookup field on the Invoice record that points to merchandise. Below I called it merchandiseKeyField.
Hope this helps.
trigger createinvoice on Merchandise2__c (after insert,after update) {
//if you don't remove after Update then check which trigger
if(Trigger.IsInsert){
list<Invoice2__c> invoices = new list<Invoice2__c>();
for(Merchandise__c mer: trigger.new){
invoices.add(new Invoice2__c(li.name = mer.name,
li.merchandiseKeyField = mer.id);
}
insert invoices;
}
}
replace your loop with this:
for(Merchandise2__c mer:Trigger.new){
Invoice2__c li = new Invoice2__c();
li.name = mer.Name;
li.Status__c='open';
line.add(li);
}

Apex Trigger-Salesforce before insert

I have two custom objects 1. Customer 2.Complaint and they are lookup relationship with each other.
I have problem like that the below trigger is not working.
My requirement is like that before inserting complaint, first it will check email id and contact number and then complaint will register.
trigger Demo on Complaint__c (before insert) {
Set<Id> customerIds = new Set<Id>();
for (Shan__Complaint__c complaint : Trigger.new) {
customerIds.add(complaint.Shan__customer__c);
}
Map<String, Shan__cust__c> customers =
new Map<String, Shan__cust__c>([SELECT Shan__cust_contact__c, Shan__cust_email__c
FROM Shan__cust__c WHERE id IN: customerIds]);
for (Shan__Complaint__c complaint : Trigger.new) {
Shan__cust__c customer = customers.get(complaint.Shan__customer__c);
if (customer == null || complaint.Shan__E_mail__c == customer.Shan__cust_email__c
&& complaint.Shan__Phone_Number__c == customer.Shan__cust_contact__c) {
complaint.adderror('Your phone and Email does not exists in out database ');
}
}
}
This trigger should not be compiled at all.
You should see error
Loop variable must be of type Complaint__c
Trigger.new is a List<Complaint__c>
So, there are 2 errors:
for (Shan__Complaint__c complaint : Trigger.new) {
customerIds.add(complaint.Shan__customer__c);
...
for (Shan__Complaint__c complaint : Trigger.new) {
Shan__cust__c customer = customers.get(complaint.Shan__customer__c);
...

Resources