Salesforce passing values to Multipicklist based on another object - salesforce

long time no see, quick question about multipicklist in Apex.
Here is the condition:
1. Two standard objects: Task and Account, task is linked to account.
2. The subject field in the task contains three values: A, B, C.
3. Also, there is a field (Multipicklist)in the account contains the same values A, B, C
Every time I will create a task under a certain account, If I input subject with A, I hope the field in the account can be updated with A;
Then if I create a task with subject B, the field in the account should be (A;B)
So, here is my code:
if(IsSC && t.Status == PickListValuesStandard.Task_Completed){
Account student = new Account(Id = t.WhatId);
student.LatestCompletedActivity__pc = t.Subject;
student.LatestCompletedActivityDate__pc = t.ActivityDate;
if(t.Subject.contains('Post OC Call')){
student.Center_TouchPoints__c += (';Post OC Call');
}
if(t.Subject.contains('Third Week Call')){
student.Center_TouchPoints__c += (';Third Week Call');
}
update student;
}
The bolded part I attached above should be working like I described, Unfortunately, it didn't.
Can anyone help me understand the scenario? How can I achieve this?
Thanks in advance,

I just realized what a big mistake I've made, here is the thought, if I wanna update the multipicklist in the account, first thing first, I need to check whether it's null or not. Here is the update:
if(IsSC && t.Status == PickListValuesStandard.Task_Completed){
//Account student = new Account(Id = t.WhatId);
Account student = [select Center_TouchPoints__c from Account where Id=:t.WhatId];
student.LatestCompletedActivity__pc = t.Subject;
student.LatestCompletedActivityDate__pc = t.ActivityDate;
if(student.Center_TouchPoints__c==null){
if(t.Subject.contains('Post OC Call')){
student.Center_TouchPoints__c = 'Post OC Call;';
}
if(t.Subject.contains('Third Week Call')){
student.Center_TouchPoints__c = 'Third Week Call;';
}
}else if(student.Center_TouchPoints__c.contains ('Post OC Call') && t.Subject.contains('Third Week Call')){
student.Center_TouchPoints__c += ';Third Week Call';
}
update student;
}
However, if anyone of you has any better idea, please shoot me!

One way that might make this a bit more flexible is to loop through all the available values in the picklist and see if the task's subject contains that picklist value and if it does add that to the selected picklist values. This is assuming the name or label of the picklist entries match the values entered into the subject of the task. This way you will be able to add different entries or change the picklist values without changing the code. Here is an example of getting and looping through all picklist values
here's how I think that would look...
if(IsSC && t.Status == PickListValuesStandard.Task_Completed){
Account student = [select Center_TouchPoints__c from Account where Id=:t.WhatId];
student.LatestCompletedActivity__pc = t.Subject;
student.LatestCompletedActivityDate__pc = t.ActivityDate;
Schema.DescribeFieldResult fieldDescribe = account.Center_TouchPoints__c.getDescribe();
//retrieves picklist values
List<Schema.PicklistEntry> picklistVals = fieldResult.getPicklistValues();
String picklistString = '';
for(Schema.PicklistEntry plv : picklistVals){ //Loop through picklist values
if(t.subject.contains(plv.getValue()) && !student.Center_TouchPoints__c.contains(plv.getValue())) {
//If if this picklist value is in the subject and it hasn't been selected already add it.
picklistString += (plv.getValue() + '; ');
}
}
if(student.Center_TouchPoints__c == null)
student.Center_TouchPoints__c = picklistString.substring(1);
else
student.Center_TouchPoints__c += (';' + picklistString);
update student;
}
Hope this helps!

Related

Update Parent Object Field in Apex Trigger

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.

Check string value in salesforce test class

Below is the code for my test class.
Opportunity opp = [select Deal_Type__c from opportunity where Id: = <some id>];
Case objCase = new Case();
objCase.standard_or_nonstandard__c = 'Yes';
if(objCase.standard_or_nonstandard__c = 'Yes'){ // this if is getting tested
opp.Deal_Type__c = 'Standard';
}
else{ // else part is getting skipped
opp.Deal_Type__c = 'Not Standard';
}
And only first if condition is getting tested and other is skipping which is why the code is not reaching 75% off code coverage.
the field standard_or_nonstandard__c is picklist having two values Yes & No.
And if the value if Yes, the deal type should be standard, and if No, the deal type is not standard.
Any suggestion on this?
Because you're setting the field objCase.standard_or_nonstandard__c to 'Yes' before the condition. This means that there is no way for the field to be equal to 'No' when the condition is evaluated. So the first 'if' block is always entered and the else condition never is. You'll need to remove that line ( objCase.standard_or_nonstandard__c = 'Yes';) before the If statement in order for test data to be able to enter the else block.
You need to make some changes in your code to cover 75% code coverage.
you should try this one:
Opportunity opp = [select Deal_Type__c from opportunity where Id: = <some id>];
Case objCase = new Case();
objCase.standard_or_nonstandard__c = 'Yes';
opp.Deal_Type__c = 'Not Standard';
if(objCase.standard_or_nonstandard__c == 'Yes'){ // this if is getting tested
opp.Deal_Type__c = 'Standard';
}
Thanks,
Ajay Dubedi

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

how to aggregate records in a list

I have a batch program that I need to aggregate (rollup) several currency fields by a specific contact and fund. I need a fresh set of eyes on this as I can't figure out how I need to correctly rollup the fields by the contact and fund.
Here is my current code in the batch program:
for (My_SObject__c obj : (List<My_SObject__c>)scope) {
if(!dbrToContactMap.isEmpty() && dbrToContactMap.size() > 0) {
if(dbrToContactMap.containsKey(obj.DBR__c)) {
List<Id> contactIds = dbrToContactMap.get(obj.DBR__c);
for(Id contactId : contactIds) {
My_Rollup__c rollup = new My_Rollup__c();
rollup.Fund_Name__c = obj.FundName__r.Name;
rollup.DBR__c = obj.DBR__c;
rollup.Contact__c = contactId;
rollup.YearToDate__c = obj.YearToDate__c;
rollup.PriorYear__c = obj.PriorYear__c;
rollupsToInsert.add(rollup);
}
}
}
}
if(!rollupsToInsert.isEmpty() && rollupsToInsert.size() > 0) {
insert rollupsToInsert;
}
I'm iterating over the scope of records, which is about 275,000 records that are returned. I have a map that returns a list of contacts by the key field in my scope.
Now, currently, as I loop over each contact, I put those into a list and insert. The problem is I need to aggregate (rollup) by fund and contact.
For example, let's say the map returns the contact for "John Doe" ten times for the specific key field. So, there are going to be 10 related records on "John Doe's" contact record.
The problem is that the same fund can be in those 10 records, which need to be aggregated.
So, if "Fund A" shows up 5 times and "Fund B" shows up 3 times and "Fund C" shows up 2 times, then I should only have 3 related records in total on the "John Doe" contact record that are aggregated (rolled up) by the fund.
I haven't been able to figure out how to do the rollup by fund in my list.
Can anyone help?
Any help is appreciated.
Thanks.
The key here is to use a stringified index key for your map, instead of using a raw Sobject ID. Think of this as a composite foreign key, where the combined values from a Fund and a DBR are joined. Here is the basic idea:
Map<String, My_Rollup__c> rollupMap = new Map<String, My_Rollup__c>();
for (My_SObject__c obj : (List<My_SObject__c>) scope) {
// .. stuff ..
String index = '' + new String[] {
'' + obj.FundName__r.Id,
'' + obj.DBR__c,
'' + contactId
};
// Find existing rollup, or create new rollup object...
My_Rollup__c rollup = rollupMap.get(index);
if (rollup == null) {
rollup = new My_Rollup__c();
rollupMap.put(index, rollup);
}
// Aggregate values..
}
// And save
if (rollupMap.isEmpty() == false) {
insert rollupMap.values();
}
The result is that you combining all the different "keys" that makeup a unique rollup record into a single stringified key, and then using that stringified key as the index in the map to enforce uniqueness.
The example above is incomplete, but you should be able to take it from here.

Resources