+ Start a Discussion
ScottishCalvinScottishCalvin 

Working through a list by date

 

Just starting to delve into the SF world; getting the feeling there's a lot of good resources, once you get over the initial steep learning curve.

 

I'm wanting to add a trigger so that when a new set of inventory and price are added, the system adds in the previous figures added in.  That way you can calculate the movements and plot out the results as an up/down pattern.

 

I thought I can then scan through each of the entries and copy the previous price and inventory into the next entry as the "previous price" etc.  That means I could add formula fields like 'large increase' or flag things for review.  Yes the end result could be done by comparing the dates modified but I want the ability to backfill the data at a later date so I need to be able to loop through the list in order of delivery date (date is a custom field in the object btw).

 

I think I'm right in saying that I can't do a sort on a custom object though.  I suppose that the for() loop might not necessarily go from start to finish or top to down if you know what I mean.  I'm not sure where I go from here or if my bet bet is to make a new list, fill it with the dates, sort that and then run the two against each other?  This is what I had so far

 

Trigger FetchPreviousDaysInfo on Delivery_Data__c (before insert, after update )
{
List <Delivery_Data__c> DeliveryData =
[
Select
ii.Date__c,
ii.Price__c,
ii.Stocks__c,
ii.Previous_Price__c,
ii.Previous_Stocks__c
From Delivery_Data__c ii
For Update
];

DeliveryData.sort(DeliveryData.Date__c);

 

Double LastPrice = 0;
Double LastStocks = 0;

 

for(Delivery_Data__c TheEntry: DeliveryData)
{
     if (LastPrice <> 0)
     {
         TheEntry.Previous_Price__c = LastPrice;
         TheEntry.Previous_Stocks__c = LastStocks;
     }
     LastPrice = TheEntry.Price__c;
     LastStocks = TheEntry.Stocks__c;

}

 

update DeliveryData;
}

WizradWizrad

This trigger could be problematic depending on the quantity of Delivery_Data__c records in your system.

 

You can accomplish a sort by date and fix the issue with querying for too many records by changing your initial query to:

 

List <Delivery_Data__c> deliveryData =
[
Select
ii.Date__c,
ii.Price__c,
ii.Stocks__c,
ii.Previous_Price__c,
ii.Previous_Stocks__c
From Delivery_Data__c ii
Where Id in :Trigger.new
Order by Date__c desc
];

 

ScottishCalvinScottishCalvin

Ah right, adding the Order By worked after I removed the "For Update" bit it said I needed in the booklet.  Is that not a necessary line after all?