function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
DILEEP NALLADILEEP NALLA 

needs previous value record in current records filed using triggers on and using salesforce admin

User-added image


Hi
I have a below requirement,
I have created an object for calculating mileage vs cost for bike
I have the below fields in my object:
 Object Name:
API NameMileage_vs_Cost__c
Bill AmountBill_Amount__c
Current ReadingCurrent_Reading__c
DateDate__c
Past ReadingPast_Reading__c
PetrolUserName__c
Petrol User is a master object for( Mileage_Vs_ Cost__c) object
Example : For the first time when I save my record, current reading is zero fueled on 3/21/2016,
I will be travelling whole month and next time when I am ready to fuel the petrol , I will be entering some 1000 kms as current reading and when I do this process I want the past reading(i.e; previous month's current reading which is 0(zero) when I filled fuel on 3/21/2016) to  get populated in Past_reading__c filed of my record….
So that I can calculate mileage = (Current reading - past reading) and based on this further developments I can do on the page; can any one help me in this requirement I feel grateful and I am trying it using List and triggers and am failing…
Best Answer chosen by DILEEP NALLA
Mahesh DMahesh D
Hi Dileep,

Please find the modified code:
 
trigger MileageCostTrigger on Mileage_vs_Cost__c (before insert) {
	if(Trigger.isInsert) {
		Set<Id> uIdSet = new Set<Id>();
		for(Mileage_vs_Cost__c mc: Trigger.new) {
			if(mc.PetrolUser__c != null)
				uIdSet.add(mc.PetrolUser__c);
		}
		
		if(!uIdSet.isEmpty()) {
			List<Mileage_vs_Cost__c> mcList = [Select Id, Name, PetrolUser__c, Current_Reading__c from Mileage_vs_Cost__c where PetrolUser__c IN: uIdSet ORDER BY CreatedDate DESC];
			for(Mileage_vs_Cost__c mc: Trigger.new) {
				if(mc.PetrolUser__c != null) {
					for(Mileage_vs_Cost__c existMC: mcList) {
						if(mc.PetrolUser__c == existMC.PetrolUser__c) {
							mc.Past_Reading__c = existMC.Current_Reading__c;
							break;
						}
					}
				}
			}
		}
	}
}

Please do let me know if it helps you.

Regards,
Mahesh

All Answers

GauravTrivediGauravTrivedi
Dileep,

you can use before trigger and get the old value for milage calculation and manipulate it then store it in mileage field.

 
Mahesh DMahesh D
Hi Dileep,

Please find the below trigger:
 
trigger MileageCostTrigger on Mileage_vs_Cost__c (before update) {
	if(Trigger.isUpdate) {
		for(Mileage_vs_Cost__c mc: Trigger.new) {
			if(mc.Current_Reading__c != Trigger.oldMap(mc.Id).Current_Reading__c) {
				mc.Past_Reading__c = Trigger.oldMap(mc.Id).Current_Reading__c;
			}
		}
	}
}

Also look into the below best practices while writing the Triggers.

1) One Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

2) Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org.

3) Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers

4) Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5) Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6) Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

7) Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

8) Use @future Appropriately
It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

9) Avoid Hardcoding IDs
When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail


Please do let me know if it helps you.

Regards,
Mahesh
DILEEP NALLADILEEP NALLA
Thanks Mahesh,
Can you please let me know if I need to create any Map ? I am getting below error can you please suggest meUser-added image
Mahesh DMahesh D
Please take the corrected one:
 
trigger MileageCostTrigger on Mileage_vs_Cost__c (before update) {
	if(Trigger.isUpdate) {
		for(Mileage_vs_Cost__c mc: Trigger.new) {
			if(mc.Current_Reading__c != Trigger.oldMap.get(mc.Id).Current_Reading__c) {
				mc.Past_Reading__c = Trigger.oldMap.get(mc.Id).Current_Reading__c;
			}
		}
	}
}

Regards,
Mahesh
DILEEP NALLADILEEP NALLA
No Luck Mahesh, Now am free with errors but the current records is not updating p14 has current reading as 500 and p15 has current reading as 1000, i need past reading in p15 as p14 current reading i.e 500 as auto populating value :( Please let me know in case of any changes needed, your help is grateful.please find the screenshots:User-added imageUser-added image
Mahesh DMahesh D
Hi Dileep,

Please find the below modified code:
 
trigger MileageCostTrigger on Mileage_vs_Cost__c (before insert) {
	if(Trigger.isInsert) {
		Set<Id> uIdSet = new Set<Id>();
		for(Mileage_vs_Cost__c mc: Trigger.new) {
			if(mc.PetrolUser__c != null)
				uIdSet.add(mc.PetrolUser__c);
		}
		
		if(!uIdSet.isEmpty()) {
			List<Mileage_vs_Cost__c> mcList = [Select Id, Name, PetrolUser__c, Current_Reading__c from Mileage_vs_Cost__c where PetrolUser__c IN: uIdSet ORDER BY CreatedDate DESC];
			for(Mileage_vs_Cost__c mc: Trigger.new) {
				if(mc.PetrolUser__c != null) {
					for(Mileage_vs_Cost__c existMC: mcList) {
						if(mc.PetrolUser__c == existMC.PetrolUser__c) {
							mc.Past_Reading__c = existMC.Current_Reading__c;
						}
					}
				}
			}
		}
	}
}

Please do let me know if it helps you.

Regards,
Mahesh
DILEEP NALLADILEEP NALLA
Awesome Mahesh, you have almost solved my requirement... Thanks a lot for your quick help..
One more thing mahesh from the latest code given by you am getting only second saved record value for every new record, I hope List is or map is not picking up the latest value.Please note the below images...p32 has current reading as 1000 and past reading as empty as first time entry.
p33 pulled p32 current reading value as its past reading which is upto mark; but p 34 is also pulling P32 reading, it is supposed to pull p33 current reading value. Please help.
User-added imageUser-added imageUser-added imageUser-added image
Mahesh DMahesh D
Hi Dileep,

Please find the modified code:
 
trigger MileageCostTrigger on Mileage_vs_Cost__c (before insert) {
	if(Trigger.isInsert) {
		Set<Id> uIdSet = new Set<Id>();
		for(Mileage_vs_Cost__c mc: Trigger.new) {
			if(mc.PetrolUser__c != null)
				uIdSet.add(mc.PetrolUser__c);
		}
		
		if(!uIdSet.isEmpty()) {
			List<Mileage_vs_Cost__c> mcList = [Select Id, Name, PetrolUser__c, Current_Reading__c from Mileage_vs_Cost__c where PetrolUser__c IN: uIdSet ORDER BY CreatedDate DESC];
			for(Mileage_vs_Cost__c mc: Trigger.new) {
				if(mc.PetrolUser__c != null) {
					for(Mileage_vs_Cost__c existMC: mcList) {
						if(mc.PetrolUser__c == existMC.PetrolUser__c) {
							mc.Past_Reading__c = existMC.Current_Reading__c;
							break;
						}
					}
				}
			}
		}
	}
}

Please do let me know if it helps you.

Regards,
Mahesh
This was selected as the best answer
DILEEP NALLADILEEP NALLA
It Worked Mahesh; Thanks a lot for your help...
you are at your best..Cheer Up buddy..
 
Naman Jain 61Naman Jain 61
Hi Dileep,

Can you please tell me how it works. Means updating the value from previous one.

Regards,
Naman Jain
Naman Jain 61Naman Jain 61
Hi, 

I have the same type of requirement
Requirement:
Parent Object : CASE
Child object : VISIT (Master detail)

Fields on child object : 1) Visit date (date/time) 
2) Visit number (autonumber)  API name :- name
3) created date (default)
4) days_to_creation (number)

I want to update the field "days_to_creation"  with difference of prior visit date and  visit creation date

Visit Number    Created date       Visit Date            Days to Creation
V-100               08-03-2018          12-03-2018        0
v-101               09-03-2018           16-03-2018        12-03-2018 - 09-03-2018  = 3
V-102              12-03-2018            20-03-2018        16-03-2018 - 12-03-2018  = 4
V-104               14-03-2018           23-03-2018         20-03-2018 - 14-03-2018  = 6

Can any one help me in this requirement I feel grateful and I am trying it using List and triggers and but not able to do.

Trying with the above same logic but it is updating child records i.e all visits, but I just want to update the field for whcih I am updating the record...

User-added image

Regards,
Naman Jain