Salesforce Customer - salesforce

• Create a Custom Field on the Standard Object called “Accounts” on the setup menu
• Add the following custom filed
Field Name Datatype Constraint
Priority Picklist (1, 2, 3, 4, 5)
• Create a Custom Object called “Customer” on the setup menu
• Add the following custom fields
Field Name Datatype Constraint
Title Picklist (Mr, Mrs, Miss)
First_Name Text(100) Required
Last_Name Text(100) Required
Age Number
Address Text(255)
Gender Picklist(Male, Female)
Ref. Account Lookup(Account)
• Create a new Trigger class based on the newly created Custom Object “Customer” to handle duplicate Customer Records.
• Trigger should handle bulk operations as well
• Business requirement as follows:
o Trigger should handle both Insert and Update operations on “Customer”
o Title, First_Name, Last_Name combination must be unique
o At any given time, there should be only unique records in the system
o If a duplicate record found, latest record should be in the system while the previous should get deleted
o If the latest Customer record has a “Ref. Account” with lesser priority than the duplicate found record; change the “Ref. Account” of the latest Customer record to the higher priority account if found on the duplicate record. Always the latest customer record should have the highest priority account with respective to its duplicate. (Note: Priority 1 is the min, Priority 5 is the max)
Please try to provide Answer for this in Salesforce solution as soon as possible. Please advice how to delete and add new record in triggers.

I have done up to handle duplicate records and delete duplicate records.I stuck with get Ref.Account with lesser priority account. how to access Account object priority field and compare with current record Account Priority field? Please reply as soon as possible.
trigger CustomerTigger on Customer__c(Before insert, Before update) {
List < Customer__c > StaActiList = [Select ID, First_Name__c, Last_Name__c, Title__c, Address__c, Gender__c, RefAccount__c
from Customer__c];
for (Customer__c opp: Trigger.new) {
for (Customer__c sa: StaActiList) {
try {
if (sa.First_Name__c == opp.First_Name__c && sa.Last_Name__c == opp.Last_Name__c && sa.Title__c == opp.Title__c) {
List < Id > lstId = new List < Id > ();
List < Customer__c > existoppList = [Select Id from Customer__c where Id = : sa.Id];
delete existoppList;
}
} catch (Exception Ex) {
}
}
}
}

Related

Salesforce get all objects that changed after some date

I would like to keep an updated copy of some salesforce data in a database.
e.g. a table with all contacts
However, it is impractical to truncate the table and to query all data again on a frequent basis.
Is there some way to only query changed contacts since the last sync?
e.g. I would run an hourly job that gets all contacts that changed within the last hour.
In addition, how could I deal with deleted contacts. I assume that if there is a way to get changed ones this might not include deletions.
To query all contacts modified since a particular date/time:
Datetime OneHourAgo = System.now().addHours(-1);
List<Contact> AllContactsModfiedSinceDateTimeX = [SELECT Id FROM Contact WHERE SystemModStamp >= : OneHourAgo];
Same query but including all deleted contacts:
Datetime OneHourAgo = System.now().addHours(-1);
List<Contact> AllDeletedContactsModfiedSinceDateTimeX = [SELECT Id FROM Contact WHERE SystemModStamp >= : OneHourAgo AND isDeleted = TRUE ALL ROWS]; //"ALL ROWS" must be included when using isDeleted = TRUE

Salesforce Apex Trigger - Calculate the sum of amount field values and update Opportunity field

My title for this post might be little confusing but i will try to make it as clear as possible. I am running into an issue with Apex trigger. We have a custom object called Receivables (Managed Packaged). Each Opportunity relates with one or more receivable record. Master Detailed Relationship is not an option since Receivable object is managed packaged.
Here is my logic:
Create a trigger on Opportunity (insert and/or update) > Loop all receivables which have matching id with triggered opportunity id and Receivable Opportunity field id (This is an Opportunity look up field in Receivables) >
Use aggregated to sum the amount > Auto Populate Total Commission field.
Trigger does not throw any error but it is not auto populating as well.
trigger newRecaivables on Opportunity (after insert, after update)
{
set<Id> oppid = new set<id>();
list<opportunity> opplist = [select id from opportunity where id in : oppid ];
for(Opportunity Opp : trigger.new)
{
List<aggregateResult> results = [select Fees_Received_Category__c ,sum(McaApp__Amount__c) total from McaApp__Receivable__c Where McaApp__Opportunity__c in:oppid group by Fees_Received_Category__c];
for(AggregateResult ar : results)
{
if (String.valueOf(ar.get('Fees_Received_Category__c'))=='Received')
{
Opp.Total_Commission__c = String.valueOf(ar.get('total'));
}
}
}
}
Any help would be appreciated.
Your trigger should fire on before insert, before update.
Since you're operating on the trigger.new enumeration, that will set the proper value when the object is either first created or updated separately.

How do I retrieve a related object using a Lookup field in Apex?

I have a trigger for insert on Opportunity:
trigger OpportunityInsertTrigger on Opportunity (before insert) {
System.debug('Triggered on insert of opportunity. Updating blockchain...');
for (Opportunity opp : Trigger.new) {
List<DNBCompany__c> retrievedCompany = [SELECT Id, Name, Duns__c FROM DNBCompany__c WHERE Id = :opp.DNBCompany__c];
DNBCompany__c company = retrievedCompany.get(0);
String duns = (String) company.get('Duns__c');
}
}
I have a custom object called DNBCompany that is linked via a Lookup relation (DNBCompany__c) in Opportunity.
How can I retrieve the DNBCompany associated with opp?
[EDITED to reflect answer below]
You could do something like this :
for (Opportunity opp : Trigger.new)
{
DNBCompany__c retrievedCompany = [SELECT Id, Name FROM DNBCompany__c WHERE Id = :opp.DNBCompany__c];
}
Since the lookup field will be the Id of the company you want to retrieve, you can use an inline SOQL query to get the associated object back.
Keep in mind, you'll have to reference any additional fields you wish to process on in your SOQL query.

Not creating all records

In apex-code i have wrote 2 triggers. I have 2 objects A and B. I need to create records of B object when A object is created. For eg: When 1 record of Object A is created then then create 4 records of object B. I have wrote 2 trigger 1 is for default some fields in B object when A object is created (this is before insert, before update) trigger and 2 trigger is to create record of object B when record of A is created(this is after insert, after update) trigger.
But when i create i record of Object A then 4 record id created.
But when used Apex Data Loader to create records of object A at that time 2 records are created for A but for B object only 4 records are create. This is created for the second record of the A object.
i changed the code to
for(Object e : Trigger.new){
for(){
create 4 records for B object
}}
I am getting this error when i did it
Insert failed. First exception on row 0 with id abcdef12345; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]
Can any body help me to solve the problem.
Thanks
Anu
The error message is telling you that you cannot assign a value to the ID field. The ID field is protected and the value for it is auto-generated by Salesforce.com.
Remove ID field from your insert statement.
Id isn't populated yet during a before insert trigger so you may be referencing it too early, maybe trying to point the B records back at the A records. Another problem would be trying to assign a value to B.Id. Both code problems are illustrated below:
trigger trigA on A__c (before insert) {
List<B__c> listB = new List<B__c>();
for (A__c a : trigger.new) {
B__c b = new B__c();
B__c.reference_to_A__c = a.Id; // <-- Wrong! a.Id isn't populated yet in before insert
B__c.Id = '...'; // <-- Wrong! Salesforce generates the Id field for you
listB.add(b);
}
insert listB;
}
It would be helpful to see more of your code.

Salesforce:Add record to a field which is dependent on the input of other field

I have an object named 'Salary'. There are three fields in it- 'Add Salary', 'Month' and 'Available Salary'. Also there is a lookup relationship from Salary object to 'User Name' object. For every user there is a salary record for every month. Whenever salary is added to a particular user's record, the available salary should show the sum of salaries of previous months. How can I do that?? Please suggest me....Thanks.
The easiest way would be to change the Lookup Relationship to a Master-Detail Relationship and use a Roll-Up Summary field on the User object (Setup > Customize > Users > Fields > User Custom Fields > New).
Alternatively, you could use a Trigger on the Salary object, but only do that if you absolutely need additional functionality that cannot be accomplished with a Roll-Up Summary or other configuration.
Here's an example of using a Trigger. I haven't tried compiling it, so there will inevitably be some compile errors, but it's a place to start.
trigger AddSalary on Salary__c (after update) {
// create a set of all the unique User Ids
Map<Id,List<Salary__c>> SalaryByUserId = new Map<Id,List<Salary__c>>();
for(Salary__c s : Trigger.new)
{
List<Salary__c> SalariesForUser = SalaryByUserId.get(s.User__c);
if(SalariesForUser == null)
{
SalaryByUserId.put(s.User__c,new Salary__c[]{s});
}
else
{
SalariesForUser.add(s);
SalaryByUserId.put(s.User__c,SalariesForUser);
}
}
// query for all the User records for the unique UserIds in the records
// create a map for a lookup / hash table for the User info
Map<Id,User> Users = new Map<Id,User>(
[Select Id, Username, Available_Salary__c From User Where Id IN SalaryByUserId.keyset()]);
// iterate over the list of records being processed in the Trigger and add the Salaries to the Users
for (Id i : SalaryByUserId.keyset())
{
User u = Users.get(i);
Decimal TotalSalary = 0;
for(Salary__c s : SalaryByUserId.get(u.Id))
{
TotalSalary += s.Monthly_Salary__c;
}
Users.get(u.Id).Total_Salary__c = TotalSalary;
}
update Users;
}

Resources