How access the freight__c object from the Order in the OrderItem trigger in Salesforce? - triggers

I'm new to Salesforce development and I'm having trouble executing this trigger module challenge for the course I'm taking.
The challenge consists in making a trigger in the OrderItem that after Inserting or Update of some product fills the Freight__c field of the Order object automatically, and this is where my difficulty lies.
I am accessing the Order Object within the OrderItem Trigger from a Set orderId, and within the orderMap MAP I have access to the Account Object and Freight__c, I have to access the Account object, because the Freight must be chosen from the Account location.
public static List<Order> calculeFreight(List<OrderItem> orderItemList){
Set <Id> orderIdSet = new Set <Id> ();
for(OrderItem orderItem : orderItemList){
orderIdSet.add(orderItem.OrderId);
}
Map<Id, Order> orderMap = new Map<Id, Order>([
SELECT Id, AccountId, Account.CEP__c, Account.City__c,
Freight__c, Freight__r.CEP__c,Freight__r.City__c, DistributionCenter__c, Freight__r.DistributionCenter__c
FROM Order
WHERE Id IN: orderIdSet
]);
System.debug('orderMap=>'+ orderMap); // debug orderMap don't return Freight
this code snippet is part of the calculeFreight method, the main method, there is also the searchFreight method, which compares the location of Account and Freight, but the problem is still in the orderMap.
After executing the Trigger, the freight field is still empty, I did a debug test to see what the result of the orderMap was, but it didn't return any freight because the freight is empty in the Order
Note: The field Freight of the Order is of type Lookup

Related

Trigger on Notes object is not firing

trigger LMDofNotes on Note (after insert, after update) {
Id accountId;
Date LMDofNote;
for(Note att: Trigger.new){
accountId = att.ParentId;
LMDofNote= (Date)att.LastModifiedDate;
}
Account acc = [Select Id,LMD_of_Notes__c from Account where Id=:accountId LIMIT 1];
acc.LMD_of_Notes__c = LMDofNote;
update acc;
system.debug('updated date'+LMDofNote);
}
Orgs with Enhanced Notes active do not create Note records, which represents classic Notes.
Instead, they create ContentNote records, which are part of a much more complex ERD. ContentNote doesn't have a ParentId field (its relationship to records is many-to-many), so your trigger would have to be on the ContentDocumentLink object.
ContentNote is basically a facade on the underlying ContentDocument and ContentVersion objects, but you can identify the note records by the FileType field:
All notes have a file type of SNOTE.
Be aware that ContentDocumentLink is used for linking all Content records (not just notes) to sObjects, and that there are unique restrictions on querying it that are described in the documentation linked above.

Trigger to prevent User From Adding more than one product to an opportunity

So i have written a trigger to prevent user from entering more than one opportunity product to the same opportunity, but the problem is when he adds more than one opportunity product at the same time, my trigger does not fire, salesforce takes it as one product.
What can i add to my trigger to fix this ?
My trigger :
trigger OpportunityLineItemBeforeInsert on OpportunityLineItem (before insert) {
Set<Id>opportunityIds = new Set<Id>();
// get all parent IDs
for(OpportunityLineItem i : trigger.new)
{
opportunityIds.add(i.OpportunityId);
}
// query for related Olis (Opportunity Line Items)
Map<Id, Opportunity> opps = new Map<Id, Opportunity>([SELECT ID,
(SELECT ID
FROM OpportunityLineItems)
FROM Opportunity
WHERE ID IN :opportunityIds]);
for(OpportunityLineItem i : trigger.new)
{
if(opps.get(i.OpportunityId).OpportunityLineItems.size()>0)
{
i.addError('Your Message');
}
}
}
Thank you in advance.
I would probably ignore anything related to the Oppty.
You want only one product created, so on creation, either the number of LI is 0 and you can create exactly one, or it' snot 0 and you can't create any.
I would just create a rollup field on the Oppty, count the products. If the count != 0, then fail the validation. If count = 0, then count the Olis in trigger.new and if !=1, fail.
Instead of writing code to do this you should instead create a field on products that stores the id of the parent opportunity, make that field unique, and populate the value via workflow or process builder with the id of the parent opportunity. That way if a second product gets added the unique constraint would fire and prevent the record from being inserted.
Another option would be to create a rollup on opportunity to count the number of opportunity products, then add a validation rule that show an error if the number of products > 1. The advantage of doing it this way is that you get to set the error message as opposed to the generic duplicate error message with the first option.

Apex code to update new Opportunity with values from related object

What would be the proper method to update a list of new Opportunities with the values from a related record.
for (Opportunity opps:Trigger.new){
[SELECT Id, CorpOwner__r, Contact__r,(SELECT Id, AccountLocation from Account)]
o.CorpOwner__r =Account.Id; o.AccountLocation = opps.Account.AccountLocation;
insert opps
Do you call the lookup fields by the __r suffix? Could you do a before insert operation and still look up the Opportunity.CorpOwner__r relationship to values in the CorpOwner__r Account record, or does that relationship not exist since the record has not been created? What would be a proper batchified way to go about it?
Here's a possibility that demonstrates a number of concepts:
trigger UpdateOpptyWithAccountInfo on Opportunity (before insert) {
// Keep this SOQL query out of the FOR loop for better efficiency/batching
Map<Id, Account> relatedAccounts = new Map<Id, Account>(
[SELECT Id, AccountLocation__c
FROM Account
WHERE Id IN
(SELECT AccountId
FROM Opportunity
WHERE Id = :Trigger.new)
]
);
for (Opportunity o : Trigger.new) {
/* Find each opportunity's Account in the map we queried for earlier
* Note: there's probably a more efficient way to use a Map of Opportunity IDs to Account objects...
* This works fine and could be more readable.
*/
for (Account a : relatedAccounts.values()) {
if (a.Id == o.AccountId) {
// Once you've found the account related to this opportunity, update the values
o.CorpOwner__c = a.Id;
o.AccountLocation__c = a.AccountLocation__c;
}
}
}
// We're still inside an `insert` trigger, so no need to call `insert` again.
// The new fields will be inserted along with everything else.
}
If you're establishing the relationship between objects, use the __c suffix:
o.CorpOwner__c = a.Id; // Associate Account `a` as Opportunity `o`'s CorpOwner
If you're looking up a field on a related object, then you would use __r:
System.debug(o.CorpOwner__r.Name); // Print Opportunity `o`'s CorpOwner's name

Apex Trigger to Update Lookup Field (Contact)

Need some advise on how to populate a lookup field (contact) via apex trigger
I've created a lookup field called Contact__c on Idea object.
I would like to populate the Contact__c with the createdby User if it was originated from the web (CreatedBy.Contact.Account.Name == "Web Ideas") and leave it empty for internal idea creation.
I have read up and created the following trigger and was able to save and run. However, upon saving the idea record, i am getting an error : UpdateContactonComplaints: data changed by trigger for field Contact: id value of incorrect type: 005N0000000l9iMIAQ
trigger UpdateContactonComplaints on Idea (before insert, before Update) {
list<id> oid = new list<id>();
for(Idea o: trigger.new){
oid.add(o.id);
}
map<id, Idea> ExtendU = new map<id, Idea>(
[select CreatedbyID from Idea where id in: oid]);
for(Idea o: trigger.new){
o.Contact__c = ExtendU.get(o.id).CreatedbyID;
}
}
In the Trigger, the user id(id of the User who created the idea) is assigned to Contact custom lookup field).
So, it throws an error, data changed by trigger for field Contact: id value of incorrect type:

Trigger to update a custom lookup field on opportunity

I created a custom object XtendedUser which has an id and Name.
I created a custom lookupfield on Opportunity called "XtendedUser__c" which links the opportunity to the corresponding XtendedUser record.
Now I made it so that the name of an opportunityowner corresponds to the name of an XtendedUser-record, so I want the trigger to autopopulate the custom lookup field "XtendedUser__c" on the opportunity with the id of the corresponding XtendedUser-record of which the name matches the name of the opportunityowner.
I never wrote a trigger, always worked with workflows and fieldupdates, but I've got to make this work. So if you could please help me with this? I would be extremely greatfull!
Thanks in advance
You should use a map to link the records and retrieve the value before the insert of a new record and before the update of an existing record. This technique will also allow you to bulk update all your records. It should be something like:
trigger ExtendedUser__c on Opportunity (before insert, before Update) {
list<id> oid = new list<id>();
for(opportunity o: trigger.new){
oid.add(o.id);
}
map<id, ExtendedUser__c> ExtendU = new map<id, ExtendedUser__c>(
[select name from ExtendedUser__c where id in: oid]);
for(opportunity o: trigger.new){
o.name = ExtendU.get(o.id).name;
}
}