• Russell baker 1
  • NEWBIE
  • 175 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 56
    Questions
  • 84
    Replies
I have a formula field on Account to calculate survey score. I want to calculate Average of all child account + Parent account survey scores and show that Avg. survey score on Parent account.

I have a trigger but it is showing only 1 child account survey score. Please help me to figure out the code.
Please find below code.
 
trigger childaccount on Account (after update) 
{
Set<String> SetParentId = new set<String>();
Decimal Num;
for (Account a : trigger.new)
{
    if(a.parentId != null)
    {
        SetParentId.add(a.parentId);
    }
}

if(SetParentId.size() > 0 )
{
    List<Account> lstParentAcc = [ Select NPS_Score__c, Group_NPS__c , (Select NPS_Score__c From ChildAccounts) From Account where id in :SetParentId ];    

    For (Account ac : lstParentAcc)
    {
        List<Account> lstChildAcc = ac.ChildAccounts;

        for( Account childAcc : lstChildAcc )
        {
            Num = childAcc.NPS_Score__c;
        }
        ac.Group_NPS__c = Num;
    }
    if(lstParentAcc.size() > 0 )
    {
        update lstParentAcc;
    }   
   }   
  }
How can I get avg. of all child account and parent account survey score.
 
I have a requirement. Contact related to Task, I need to pull his functional role ( custom field) on Activity page layout. So whenever I create or edit an activity and relate with ant contact so his/her functional role should populate automatic.

Please help! How can I achieve it? I tried formula field but unable to get. I tried through trigger but it is not working nighter on new task nor while I update the task.
Please find below code:
 
trigger updatefunctionalrole on Task (before insert, before update) {

Map<ID,String> confunrole = new Map<ID,String>();
List<Task> conTasks = new List<Task>();


for (Task e : trigger.new) {

    if (e.whoID!= null && (String.valueOf(e.whoID)).startsWith('003'))  {

        if (trigger.isInsert || (trigger.isUpdate && e.WhoID != trigger.oldMap.get(e.id).WhoID)) {
            confunrole.put(e.whoID,'');
            conTasks.add(e);
        }
    }
}

for (contact con : [SELECT Functional_Role__c FROM contact WHERE ID IN :confunrole.keySet()]) {
    confunrole.put(con.id,con.Functional_Role__c);
}
// Update the contact functional role field on the Task with the relevant value
for (Task e : trigger.new) {
    e.functional_role__c = confunrole.get(e.whoID);
}
}
Kindly let me me know where I am doing wrong.
 
I have custom formula field return type date name "Last Activity date" on opportunity It is showing me Last Activity date. I want to capture "last to last Activity date". So I create a custom date field name " last to last activity date" and tried to update via workflow with "created and every time edited" and formula evaluated true. formula is <IsChanged (Last_Activity_due_date__c)>
workflow action is field update "Last to Last Activity Date"(Last_to_Last_Activity_Date) date type Date and formula is
<PRIORVALUE(Last_Activity_due_date__c)>

But It is not updating the Last to Last Activity Date field. I am thinking formula field change does not work with workflow. So i think befor trigger can solve my purpose.
Please help me  to write a trigger.

 
I have a requirement. Contact related to Task, I need to pull his functional role ( custom field) on Task page layout. So whenever I create or edit a Task and relate with any contact so his/her functional role ( Custom field) Value should populate automatic on Task Page field( Functional role).

Please help! How can I achieve it? I tried formula field but unable to get. I tried through trigger but it is not working. Please check my code and let me know what I am doing wrong.

Please find below code:
 
trigger updatefunctionalrole on Task (before insert, before update) {

Map<ID,String> confunrole = new Map<ID,String>();
List<Task> conTasks = new List<Task>();


for (Task e : trigger.new) {

    if (e.whoID!= null && (String.valueOf(e.whoID)).startsWith('003'))  {

        if (trigger.isInsert || (trigger.isUpdate && e.WhoID != trigger.oldMap.get(e.id).WhoID)) {
            confunrole.put(e.whoID,'');
            conTasks.add(e);
        }
    }
}

for (contact con : [SELECT Functional_Role__c FROM contact WHERE ID IN :confunrole.keySet()]) {
    confunrole.put(con.id,con.Functional_Role__c);
}
// Update the contact functional role field on the Task with the relevant value
for (Task e : trigger.new) {
    e.functional_role__c = confunrole.get(e.whoID);
}
}

 
 I have an issue. I have last activity age by using (Today()-Lastactivityage) to calculate last activity age. But I want to segregate it as last task age and last Event age. I have two custom field on opportunity last task age and last event age. I want age of last task when it was done or upcoming. same with event
How can I get these to age in opportunity. Please help!
I have a requirement. Contact related to Task, I need to pull his functional role ( custom field) on Activity page layout. So whenever I create or edit an activity and relate with ant contact so his/her functional role should populate automatic.

Please help! How can I achieve it? I tried formula field but unable to get. I tried through trigger but it is not working nighter on new task nor while I update the task.
Please find below code:
trigger updatefunctionalrole on Task (before insert, before update) {

Map<ID,String> confunrole = new Map<ID,String>();
List<Task> conTasks = new List<Task>();


for (Task e : trigger.new) {

    if (e.whoID!= null && (String.valueOf(e.whoID)).startsWith('003'))  {

        if (trigger.isInsert || (trigger.isUpdate && e.WhoID != trigger.oldMap.get(e.id).WhoID)) {
            confunrole.put(e.whoID,'');
            conTasks.add(e);
        }
    }
}

for (contact con : [SELECT Functional_Role__c FROM contact WHERE ID IN :confunrole.keySet()]) {
    confunrole.put(con.id,con.Functional_Role__c);
}
// Update the contact functional role field on the Task with the relevant value
for (Task e : trigger.new) {
    e.functional_role__c = confunrole.get(e.whoID);
}
}
Kindly let me me know where I am doing wrong.
 
I have a requirement. Contact related to activity, I need to pull his functional role ( custom field) on Activity page layout. So whenever I create an activity and relate with ant contact so his/her functional role should populate automatic.

Please help! How can I achieve it? I tried formula field but unable to get. I tried through trigger but it is not updating the field.
 
trigger updatefunctionalrole on Event (before insert, before update) {
// Create a map between the contact ID and its functional role value
Map<ID,String> confunrole = new Map<ID,String>();
List<Event> conEvents = new List<Event>();

// Loop through the triggered Events and add all of the contact IDs (for those associated with conortunities)
for (Event e : trigger.new) {
    // Only Events associated with contact
    if (e.whoID!= null && ((String)e.whoID).startsWith('003 ')) {
        // And only newly inserted events or those being reparented to an contact
        if (trigger.isInsert || (trigger.isUpdate && e.WhoID != trigger.oldMap.get(e.id).WhoID)) {
            confunrole.put(e.whoID,'');
            conEvents.add(e);
        }
    }
}
// Query the contact and add their functional role to the map
for (contact con : [SELECT Functional_Role__c FROM contact WHERE ID IN :confunrole.keySet()]) {
    confunrole.put(con.id,con.Functional_Role__c);
}
// Update the contact functional role field on the Event with the relevant value
for (Event e : conEvents) {
    e.contact_functional role__c = confunrole.get(e.whoID);
}
}

 
Hi Experts,

I wrote a batch class to send email to opps owner when opportunity'c close date passed.
global class SendEmailToopsowner implements Database.Batchable<sObject>  {
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator([SELECT Id, Name, StageName, CloseDate, Owner.name, Owner.Email FROM Opportunity WHERE CloseDate < TODAY  and (StageName != 'closed-Won' or StageName != 'closed-Lost' or StageName != 'In-Production')  ]);
    }
    
    global void execute(Database.BatchableContext BC, List<opportunity> scope){
            map<string,list<opportunity>> userEmailTasklistmap = new map<string,list<opportunity>>();
            for(opportunity opp : scope){
            if(!userEmailTasklistmap.Containskey(opp.owner.email)){
                userEmailTasklistmap.put(opp.owner.email, new list<opportunity>());
            }
            userEmailTasklistmap.get(opp.owner.email).add(opp);
            
          }  
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    
            for(string email : userEmailTasklistmap.keyset()){
                
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                list<string> toAddresses = new list<string>();
                toAddresses.add(email);
                mail.setToAddresses(toAddresses);
                mail.setSubject('Opportunity close date passed');                
                String username = userEmailTasklistmap.get(email)[0].owner.name;
                String htmlBody = '';
                
                htmlBody = '<table width="100%" border="0" cellspacing="0" cellpadding="8" align="center" bgcolor="#F7F7F7">'+
                            +'<tr>'+
                              +'<td style="font-size: 14px; font-weight: normal; font-family:Calibri;line-height: 18px; color: #333;"><br />'+
                                   +'<br />'+
                                    +'Dear '+username+',</td>'+
                            +'</tr>'+
                            +'<tr>'+
                                +'<td style="font-size: 14px; font-weight: normal; font-family:Calibri; line-height: 18px; color: #333;"> Below are the list of opportunities under your name and the close dates have to be reviewed.Could you please advise new close date and insert your comments in the remarks section. </td>'+
                            +'</tr>'+
                        +'</table>';
 
                htmlBody +=  '<table border="1" style="border-collapse: collapse"><tr><th>Clickhere</th><th>Name</th><th>StageName</th><th>CloseDate</th><th>Remark</th><th>Expected Close Date</th></tr>';
                for(opportunity opp : userEmailTasklistmap.get(email)){
                    
                    String CloseDate = '';
                    if (opp.CloseDate != null)
                        CloseDate = opp.CloseDate.format();                    
                    else
                        CloseDate = '';
                    String Name = opp.Name;
                    datetime dt = opp.CloseDate;
                    string ClosedDate = dt.format('M/d/yyyy');
                    string StageName = opp.StageName;
                    string View = URL.getSalesforceBaseUrl().toExternalForm()+'/'+ opp.id;
                    //string clickhere = view;
                    string Remark = '';
                    string Expectedclosedate = '';                    
                    htmlBody += '<tr><td>' + View +'</td><td>' + Name + '</td><td>' + StageName + '</td><td>' + CloseDate + '</td><td>' + Remark + '</td><td>' + Expectedclosedate + '</td></tr>';                    
                }
                 htmlBody += '</table><br>';
                 mail.sethtmlBody(htmlBody);
                 mails.add(mail);                    
            }
             if(mails.size()>0)
             Messaging.sendEmail(mails);
    }
    global void finish(Database.BatchableContext BC){        
    }
}

Then I tried to wrire Test class but not able to pull opportunity owner name and email  in test class. below is my test class
@isTest(seeAllData = true) 

public class SendEmailToopsownerTest  { 

static testMethod void testMethod1(){ 

        Profile pro = [SELECT Id FROM Profile WHERE Name='!Sales'];  
        User usr = new User( Alias = 'standt', Email='standarduser@tt.com',  
        EmailEncodingKey='UTF-8', LastName='Testing1', LanguageLocaleKey='en_US',  
        LocaleSidKey='en_US', ProfileId = pro.Id,  
        TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@tt.com'); 

        System.runAs(usr) { 
            Account acc = new Account(); 
                acc.Name = 'Test Account'; 
                insert acc; 
                acc=[SELECT id,Name FROM account WHERE id=:acc.Id]; 
                System.assertEquals(acc.Name,'Test Account'); 
            Opportunity opp = new Opportunity(); 
                opp.AccountId = acc.Id;  
                opp.Name = 'Testing'; 
                opp.StageName = 'Prospecting'; 
                opp.CloseDate = System.Today(); 
                opp.Owner.name = 'Testing1';
                opp.Owner.Email = 'standarduser@tt.com';				
                insert opp ; 
                opp=[SELECT id,Name,StageName,CloseDate,Owner.name,Owner.Email FROM Opportunity WHERE id=:opp.Id]; 
                System.assertEquals(opp.StageName ,'Prospecting'); 
             }
             Test.StartTest(); 
                Database.executeBatch (new SendEmailToopsownerTest (),200); 
            Test.StopTest(); 
    } 
 }

Kindly help me to write test class for it.
Hi,
I want to add red light and green ligh indicotor on Opportunity page layout. If opportunity is in On-Hold stage then it should be Red else green.
where can i get image file? and how can i show it in page layout.
Please help.
Hi Experts,
I want to send email alerts to opportunity owners when their opportunity close date passed. Let say if an opportunity owner have 4 opportunities with same close date so only one email alert should trigger with all 4 opportunity details like Opportunity name, close date and salesforce link.
I know it can be achieve by batch apex but my batch is not working. I haven't get any error. schedule job done is showing in Sechdule job view.
but Opportuntiy owner didn't get any email.
Please find below my batch:
global class SendEmailToopsowner implements Database.Batchable<sObject>  {
    map<string,list<opportunity>> userEmailTasklistmap = new map<string,list<opportunity>>();
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator([SELECT Id, Name, StageName, CloseDate, Owner.Email FROM Opportunity WHERE CloseDate < TODAY  and StageName != 'closed-Won' or StageName != 'closed-Lost'  ]);
    }
    
    global void execute(Database.BatchableContext BC, List<opportunity> scope){
        for(opportunity opp : scope){
            if(!userEmailTasklistmap.Containskey(opp.owner.email)){
                userEmailTasklistmap.put(opp.owner.email, new list<opportunity>());
            }
            userEmailTasklistmap.get(opp.owner.email).add(opp);
            
          }  
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    
            for(string email : userEmailTasklistmap.keyset()){
                
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                list<string> toAddresses = new list<string>();
                toAddresses.add(email);
                mail.setToAddresses(toAddresses);
                mail.setSubject('Opportunity close date passed');                
                String username = userEmailTasklistmap.get(email)[0].owner.name;
                String htmlBody = '';
                
                htmlBody = '<table width="100%" border="0" cellspacing="0" cellpadding="8" align="center" bgcolor="#F7F7F7">'+
                            +'<tr>'+
                              +'<td style="font-size: 14px; font-weight: normal; font-family:Calibri;line-height: 18px; color: #333;"><br />'+
                                   +'<br />'+
                                    +'Dear '+username+',</td>'+
                            +'</tr>'+
                            +'<tr>'+
                                +'<td style="font-size: 14px; font-weight: normal; font-family:Calibri; line-height: 18px; color: #333;"> You have Pending Task </td>'+
                            +'</tr>'+
                        +'</table>';
 
                htmlBody +=  '<table border="1" style="border-collapse: collapse"><tr><th>Name</th><th>StageName</th><th>CloseDate</th></tr>';
                for(opportunity opp : userEmailTasklistmap.get(email)){
                    
                    String CloseDate = '';
                    if (opp.CloseDate != null)
                        CloseDate = opp.CloseDate.format();                    
                    else
                        CloseDate = '';
                    String Name = opp.Name;
                    datetime dt = opp.CloseDate;
                    string ClosedDate = dt.format('M/d/yyyy');
                    string StageName = opp.StageName;
                    string View = URL.getSalesforceBaseUrl().toExternalForm()+'/'+ opp.id;
                    string clickhere = view;                    
                    htmlBody += '<tr><td>' + Clickhere +'</td><td>' + Name + '</td><td>' + CloseDate + '</td><td>' + CloseDate + '</td></tr>';                    
                }
                 htmlBody += '</table><br>';
                 mail.sethtmlBody(htmlBody);
                 mails.add(mail);                    
            }
             if(mails.size()>0)
             Messaging.sendEmail(mails);
    }
    global void finish(Database.BatchableContext BC){        
    }
}

Kindly help!
Hi Experts,
I have a batch class to send email reminders to task owners if their task due date are overdue with all task links. I have wrote test class and run test class for code covrage.
Code covrage 80% in sandbox but when I deployed it in production and check code covtage it is showing only 10%. Please help in this issue.
Below is my code.
 
global class SendEmailToDueDateTask implements Database.Batchable<sObject>  {
    map<string,list<task>> userEmailTasklistmap = new map<string,list<task>>();
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator([SELECT ID,createddate,what.id,Owner.Email,OwnerId,owner.name,Status,ActivityDate,Subject from Task WHERE Status != 'Completed' and owner.isactive = true and ActivityDate =: system.today() ]);
    }
    
    global void execute(Database.BatchableContext BC, List<Task> scope){
        for(Task Tsk : scope){
            if(!userEmailTasklistmap.Containskey(tsk.owner.email)){
                userEmailTasklistmap.put(tsk.owner.email, new list<task>());
            }
            userEmailTasklistmap.get(tsk.owner.email).add(tsk);
            
          }  
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    
            for(string email : userEmailTasklistmap.keyset()){
                
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                list<string> toAddresses = new list<string>();
                toAddresses.add(email);
                mail.setToAddresses(toAddresses);
                mail.setSubject('Details of tasks due for today');                
                String username = userEmailTasklistmap.get(email)[0].owner.name;
                String htmlBody = '';
                
                htmlBody = '<table width="100%" border="0" cellspacing="0" cellpadding="8" align="center" bgcolor="#F7F7F7">'+
                            +'<tr>'+
                              +'<td style="font-size: 14px; font-weight: normal; font-family:Calibri;line-height: 18px; color: #333;"><br />'+
                                   +'<br />'+
                                    +'Dear '+username+',</td>'+
                            +'</tr>'+
                            +'<tr>'+
                                +'<td style="font-size: 14px; font-weight: normal; font-family:Calibri; line-height: 18px; color: #333;">You have Pending Task</td>'+
                            +'</tr>'+
                        +'</table>';
 
                htmlBody +=  '<table border="1" style="border-collapse: collapse"><tr><th>Related To</th><th>Subject</th><th>Created Date</th><th> Due Date</th></tr>';
                for(task tsk : userEmailTasklistmap.get(email)){
                    
                    String duedate = '';
                    if (tsk.ActivityDate != null)
                        duedate = tsk.ActivityDate.format();                    
                    else
                        duedate = '';
                    String Subject = tsk.subject;
                    datetime dt = tsk.createddate;
                    string createddate = dt.format('M/d/yyyy');
                    string what = tsk.what.id;
                    string link = URL.getSalesforceBaseUrl().toExternalForm()+'/'+ tsk.id; 
                    htmlBody += '<tr><td>' + what + '</td><td>' + Subject + '</td><td>' + createddate + '</td><td>' + duedate + '</td></tr>';                    
                }
                 htmlBody += '</table><br>';
                 mail.sethtmlBody(htmlBody);
                 mails.add(mail);                    
            }
             if(mails.size()>0)
             Messaging.sendEmail(mails);
    }
    global void finish(Database.BatchableContext BC){        
    }
}

And Test class is:
 
@isTest 
public class SendEmailToDueDateTaskTest {
    static testMethod void testMethod1(){
		Profile pro = [SELECT Id FROM Profile WHERE Name='Standard User']; 
		User usr = new User(Alias = 'standt', Email='standarduser@tt.com', 
		EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
		LocaleSidKey='en_US', ProfileId = pro.Id, 
		TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@tt.com');
		System.runAs(usr) {
			Account acc = new Account();
				acc.Name = 'Test Account';
				insert acc;
				acc=[SELECT id,Name FROM account WHERE id=:acc.Id];
				System.assertEquals(acc.Name,'Test Account');
            Task tsk = new Task();
				tsk.whatId = acc.Id; 
				tsk.Subject = 'Testing';
				tsk.Status = 'In Progress';
				tsk.Priority = 'Normal';
				tsk.ActivityDate = System.today();
				insert tsk ;
				tsk=[SELECT id,Status FROM Task WHERE id=:tsk.Id];
				System.assertEquals(tsk.Status ,'In Progress');
            }
			Test.StartTest();
				Database.executeBatch (new SendEmailToDueDateTask (),200);
			Test.StopTest();
    }
 }

Please let me know why code covrage on 10%.
 
Hi, Please help me to create some fileds visible only when opportunity stage eqaul to closed Won. I have created fields but how can I make visible through condition. I know we can do it by visualforce page.
I have caredt visual force page but how can i override the standard page.

Please help!
We are running short of data storage and I can see most od the data storage used by "Email Tracking Statistics" almost 44%. I tried to delete it but I haven't get any option to delete. We were using campaign monitor earlier and this object created by campaign monitor. I tried data loader but did not get any object related this. It a manage package so how can i remove data.

Please help if any one was running with this issue.
I have a requirement where I have to add a custom picklist filed on send email page layout. I know it is not possible through standard Salesforce function. Kindly let me know if you are aware of any workaround or other approach.

Please help!

Russell
Salesforce for Outlook: Is it poosible to sync invitees's events from Salesforce to Outlook?
I am invitee in multiple events in Salesforce and all events are showing into my Salesforce calendar but when I tried to sync then to Outlook through Salesforce to Outlook events are not syncing. is it possible I can sync those events in which I am invitee? If not could you please share any approach through which I can achieve this.
Hi,
I have created some custom fields on lead object to capture alternate contact details apart from main contact.
First_Other_Contact_Name__c
First_Other_Contact_Phone__c
First_Other_Contact_Email__c
Second_Other_Contact_Name__c
Second_Other_Contact_Phone__c
Second_Other_Contact_Email__c

My requirement is when we normally convert lead so it become Account, opportunity and contact. I want those custom contacts details should become as second and third contact details under the account.
How can I achieve this. Please help!
Please find below code which is not working as expected:
trigger LeadConvert on Lead (after update) {

    map<Id, Lead> mapNewLead = trigger.newMap;
    List<Contact> lstContact = new List<Contact>();
    for(Lead objLead: mapNewLead.values())
    {
       if (objLead.isConverted == true) 
       {
         lstContact.add(new contact(LastName = objLead.First_Other_Contact_Name__c));
         lstContact.add(new contact(Phone = objLead.First_Other_Contact_Phone__c));
         lstContact.add(new contact(Email = objLead.First_Other_Contact_Email__c));
       }
    }
    insert lstContact;
}

 
I created a custom object budget and create a lookup relationship with opportunity. So one budget lookup field on opportunity and update this field according to close date via trigger. If close date within month of Jan so budget field update as “Jan”. So all Jan close date opportunity come under Jan budget.
 
My requirement is when any opportunity stage change as close won so opportunities amount should be some and populate on custom field “won amount “ on budget object. Same with open opportunities all open opportunities amount should show on “pipeline amount” custom field.   
I think trigger would be good approach but I don’t know how to query. Could you experts help me?
User-added image
I  created a custom object budget which will store company budget for every month. I created opportunity related list into budget and I want to show all opportunities into that related list according to close date. Let say if any opportunity close date is Jan so it should be show under Jan budget. How can I achieve this do I need to create trigger to pull all opportunities into budget related list.

User-added image
Hi, I created a custom object budget which will store company budget for every month. i created opportunity related list into budget and I want to show all opportunities into that related list according to close date.
Let say if any opportunity close date is Jan so it should be show under Jan budget.
How can I achieve this do I need to create trigger to pull all opportunities into budget related list.

Please suggest.
as per our company policies we don't have individual quotas. How I can show the whole company quotas in collaborative forecast.
I have a requirement. Contact related to Task, I need to pull his functional role ( custom field) on Activity page layout. So whenever I create or edit an activity and relate with ant contact so his/her functional role should populate automatic.

Please help! How can I achieve it? I tried formula field but unable to get. I tried through trigger but it is not working nighter on new task nor while I update the task.
Please find below code:
 
trigger updatefunctionalrole on Task (before insert, before update) {

Map<ID,String> confunrole = new Map<ID,String>();
List<Task> conTasks = new List<Task>();


for (Task e : trigger.new) {

    if (e.whoID!= null && (String.valueOf(e.whoID)).startsWith('003'))  {

        if (trigger.isInsert || (trigger.isUpdate && e.WhoID != trigger.oldMap.get(e.id).WhoID)) {
            confunrole.put(e.whoID,'');
            conTasks.add(e);
        }
    }
}

for (contact con : [SELECT Functional_Role__c FROM contact WHERE ID IN :confunrole.keySet()]) {
    confunrole.put(con.id,con.Functional_Role__c);
}
// Update the contact functional role field on the Task with the relevant value
for (Task e : trigger.new) {
    e.functional_role__c = confunrole.get(e.whoID);
}
}
Kindly let me me know where I am doing wrong.
 
I have custom formula field return type date name "Last Activity date" on opportunity It is showing me Last Activity date. I want to capture "last to last Activity date". So I create a custom date field name " last to last activity date" and tried to update via workflow with "created and every time edited" and formula evaluated true. formula is <IsChanged (Last_Activity_due_date__c)>
workflow action is field update "Last to Last Activity Date"(Last_to_Last_Activity_Date) date type Date and formula is
<PRIORVALUE(Last_Activity_due_date__c)>

But It is not updating the Last to Last Activity Date field. I am thinking formula field change does not work with workflow. So i think befor trigger can solve my purpose.
Please help me  to write a trigger.

 
 I have an issue. I have last activity age by using (Today()-Lastactivityage) to calculate last activity age. But I want to segregate it as last task age and last Event age. I have two custom field on opportunity last task age and last event age. I want age of last task when it was done or upcoming. same with event
How can I get these to age in opportunity. Please help!
I have a requirement. Contact related to Task, I need to pull his functional role ( custom field) on Activity page layout. So whenever I create or edit an activity and relate with ant contact so his/her functional role should populate automatic.

Please help! How can I achieve it? I tried formula field but unable to get. I tried through trigger but it is not working nighter on new task nor while I update the task.
Please find below code:
trigger updatefunctionalrole on Task (before insert, before update) {

Map<ID,String> confunrole = new Map<ID,String>();
List<Task> conTasks = new List<Task>();


for (Task e : trigger.new) {

    if (e.whoID!= null && (String.valueOf(e.whoID)).startsWith('003'))  {

        if (trigger.isInsert || (trigger.isUpdate && e.WhoID != trigger.oldMap.get(e.id).WhoID)) {
            confunrole.put(e.whoID,'');
            conTasks.add(e);
        }
    }
}

for (contact con : [SELECT Functional_Role__c FROM contact WHERE ID IN :confunrole.keySet()]) {
    confunrole.put(con.id,con.Functional_Role__c);
}
// Update the contact functional role field on the Task with the relevant value
for (Task e : trigger.new) {
    e.functional_role__c = confunrole.get(e.whoID);
}
}
Kindly let me me know where I am doing wrong.
 
I have a requirement. Contact related to activity, I need to pull his functional role ( custom field) on Activity page layout. So whenever I create an activity and relate with ant contact so his/her functional role should populate automatic.

Please help! How can I achieve it? I tried formula field but unable to get. I tried through trigger but it is not updating the field.
 
trigger updatefunctionalrole on Event (before insert, before update) {
// Create a map between the contact ID and its functional role value
Map<ID,String> confunrole = new Map<ID,String>();
List<Event> conEvents = new List<Event>();

// Loop through the triggered Events and add all of the contact IDs (for those associated with conortunities)
for (Event e : trigger.new) {
    // Only Events associated with contact
    if (e.whoID!= null && ((String)e.whoID).startsWith('003 ')) {
        // And only newly inserted events or those being reparented to an contact
        if (trigger.isInsert || (trigger.isUpdate && e.WhoID != trigger.oldMap.get(e.id).WhoID)) {
            confunrole.put(e.whoID,'');
            conEvents.add(e);
        }
    }
}
// Query the contact and add their functional role to the map
for (contact con : [SELECT Functional_Role__c FROM contact WHERE ID IN :confunrole.keySet()]) {
    confunrole.put(con.id,con.Functional_Role__c);
}
// Update the contact functional role field on the Event with the relevant value
for (Event e : conEvents) {
    e.contact_functional role__c = confunrole.get(e.whoID);
}
}

 
Hi Experts,

I wrote a batch class to send email to opps owner when opportunity'c close date passed.
global class SendEmailToopsowner implements Database.Batchable<sObject>  {
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator([SELECT Id, Name, StageName, CloseDate, Owner.name, Owner.Email FROM Opportunity WHERE CloseDate < TODAY  and (StageName != 'closed-Won' or StageName != 'closed-Lost' or StageName != 'In-Production')  ]);
    }
    
    global void execute(Database.BatchableContext BC, List<opportunity> scope){
            map<string,list<opportunity>> userEmailTasklistmap = new map<string,list<opportunity>>();
            for(opportunity opp : scope){
            if(!userEmailTasklistmap.Containskey(opp.owner.email)){
                userEmailTasklistmap.put(opp.owner.email, new list<opportunity>());
            }
            userEmailTasklistmap.get(opp.owner.email).add(opp);
            
          }  
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    
            for(string email : userEmailTasklistmap.keyset()){
                
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                list<string> toAddresses = new list<string>();
                toAddresses.add(email);
                mail.setToAddresses(toAddresses);
                mail.setSubject('Opportunity close date passed');                
                String username = userEmailTasklistmap.get(email)[0].owner.name;
                String htmlBody = '';
                
                htmlBody = '<table width="100%" border="0" cellspacing="0" cellpadding="8" align="center" bgcolor="#F7F7F7">'+
                            +'<tr>'+
                              +'<td style="font-size: 14px; font-weight: normal; font-family:Calibri;line-height: 18px; color: #333;"><br />'+
                                   +'<br />'+
                                    +'Dear '+username+',</td>'+
                            +'</tr>'+
                            +'<tr>'+
                                +'<td style="font-size: 14px; font-weight: normal; font-family:Calibri; line-height: 18px; color: #333;"> Below are the list of opportunities under your name and the close dates have to be reviewed.Could you please advise new close date and insert your comments in the remarks section. </td>'+
                            +'</tr>'+
                        +'</table>';
 
                htmlBody +=  '<table border="1" style="border-collapse: collapse"><tr><th>Clickhere</th><th>Name</th><th>StageName</th><th>CloseDate</th><th>Remark</th><th>Expected Close Date</th></tr>';
                for(opportunity opp : userEmailTasklistmap.get(email)){
                    
                    String CloseDate = '';
                    if (opp.CloseDate != null)
                        CloseDate = opp.CloseDate.format();                    
                    else
                        CloseDate = '';
                    String Name = opp.Name;
                    datetime dt = opp.CloseDate;
                    string ClosedDate = dt.format('M/d/yyyy');
                    string StageName = opp.StageName;
                    string View = URL.getSalesforceBaseUrl().toExternalForm()+'/'+ opp.id;
                    //string clickhere = view;
                    string Remark = '';
                    string Expectedclosedate = '';                    
                    htmlBody += '<tr><td>' + View +'</td><td>' + Name + '</td><td>' + StageName + '</td><td>' + CloseDate + '</td><td>' + Remark + '</td><td>' + Expectedclosedate + '</td></tr>';                    
                }
                 htmlBody += '</table><br>';
                 mail.sethtmlBody(htmlBody);
                 mails.add(mail);                    
            }
             if(mails.size()>0)
             Messaging.sendEmail(mails);
    }
    global void finish(Database.BatchableContext BC){        
    }
}

Then I tried to wrire Test class but not able to pull opportunity owner name and email  in test class. below is my test class
@isTest(seeAllData = true) 

public class SendEmailToopsownerTest  { 

static testMethod void testMethod1(){ 

        Profile pro = [SELECT Id FROM Profile WHERE Name='!Sales'];  
        User usr = new User( Alias = 'standt', Email='standarduser@tt.com',  
        EmailEncodingKey='UTF-8', LastName='Testing1', LanguageLocaleKey='en_US',  
        LocaleSidKey='en_US', ProfileId = pro.Id,  
        TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@tt.com'); 

        System.runAs(usr) { 
            Account acc = new Account(); 
                acc.Name = 'Test Account'; 
                insert acc; 
                acc=[SELECT id,Name FROM account WHERE id=:acc.Id]; 
                System.assertEquals(acc.Name,'Test Account'); 
            Opportunity opp = new Opportunity(); 
                opp.AccountId = acc.Id;  
                opp.Name = 'Testing'; 
                opp.StageName = 'Prospecting'; 
                opp.CloseDate = System.Today(); 
                opp.Owner.name = 'Testing1';
                opp.Owner.Email = 'standarduser@tt.com';				
                insert opp ; 
                opp=[SELECT id,Name,StageName,CloseDate,Owner.name,Owner.Email FROM Opportunity WHERE id=:opp.Id]; 
                System.assertEquals(opp.StageName ,'Prospecting'); 
             }
             Test.StartTest(); 
                Database.executeBatch (new SendEmailToopsownerTest (),200); 
            Test.StopTest(); 
    } 
 }

Kindly help me to write test class for it.
Hi Experts,
I want to send email alerts to opportunity owners when their opportunity close date passed. Let say if an opportunity owner have 4 opportunities with same close date so only one email alert should trigger with all 4 opportunity details like Opportunity name, close date and salesforce link.
I know it can be achieve by batch apex but my batch is not working. I haven't get any error. schedule job done is showing in Sechdule job view.
but Opportuntiy owner didn't get any email.
Please find below my batch:
global class SendEmailToopsowner implements Database.Batchable<sObject>  {
    map<string,list<opportunity>> userEmailTasklistmap = new map<string,list<opportunity>>();
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator([SELECT Id, Name, StageName, CloseDate, Owner.Email FROM Opportunity WHERE CloseDate < TODAY  and StageName != 'closed-Won' or StageName != 'closed-Lost'  ]);
    }
    
    global void execute(Database.BatchableContext BC, List<opportunity> scope){
        for(opportunity opp : scope){
            if(!userEmailTasklistmap.Containskey(opp.owner.email)){
                userEmailTasklistmap.put(opp.owner.email, new list<opportunity>());
            }
            userEmailTasklistmap.get(opp.owner.email).add(opp);
            
          }  
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    
            for(string email : userEmailTasklistmap.keyset()){
                
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                list<string> toAddresses = new list<string>();
                toAddresses.add(email);
                mail.setToAddresses(toAddresses);
                mail.setSubject('Opportunity close date passed');                
                String username = userEmailTasklistmap.get(email)[0].owner.name;
                String htmlBody = '';
                
                htmlBody = '<table width="100%" border="0" cellspacing="0" cellpadding="8" align="center" bgcolor="#F7F7F7">'+
                            +'<tr>'+
                              +'<td style="font-size: 14px; font-weight: normal; font-family:Calibri;line-height: 18px; color: #333;"><br />'+
                                   +'<br />'+
                                    +'Dear '+username+',</td>'+
                            +'</tr>'+
                            +'<tr>'+
                                +'<td style="font-size: 14px; font-weight: normal; font-family:Calibri; line-height: 18px; color: #333;"> You have Pending Task </td>'+
                            +'</tr>'+
                        +'</table>';
 
                htmlBody +=  '<table border="1" style="border-collapse: collapse"><tr><th>Name</th><th>StageName</th><th>CloseDate</th></tr>';
                for(opportunity opp : userEmailTasklistmap.get(email)){
                    
                    String CloseDate = '';
                    if (opp.CloseDate != null)
                        CloseDate = opp.CloseDate.format();                    
                    else
                        CloseDate = '';
                    String Name = opp.Name;
                    datetime dt = opp.CloseDate;
                    string ClosedDate = dt.format('M/d/yyyy');
                    string StageName = opp.StageName;
                    string View = URL.getSalesforceBaseUrl().toExternalForm()+'/'+ opp.id;
                    string clickhere = view;                    
                    htmlBody += '<tr><td>' + Clickhere +'</td><td>' + Name + '</td><td>' + CloseDate + '</td><td>' + CloseDate + '</td></tr>';                    
                }
                 htmlBody += '</table><br>';
                 mail.sethtmlBody(htmlBody);
                 mails.add(mail);                    
            }
             if(mails.size()>0)
             Messaging.sendEmail(mails);
    }
    global void finish(Database.BatchableContext BC){        
    }
}

Kindly help!
Hi,
I have created some custom fields on lead object to capture alternate contact details apart from main contact.
First_Other_Contact_Name__c
First_Other_Contact_Phone__c
First_Other_Contact_Email__c
Second_Other_Contact_Name__c
Second_Other_Contact_Phone__c
Second_Other_Contact_Email__c

My requirement is when we normally convert lead so it become Account, opportunity and contact. I want those custom contacts details should become as second and third contact details under the account.
How can I achieve this. Please help!
Please find below code which is not working as expected:
trigger LeadConvert on Lead (after update) {

    map<Id, Lead> mapNewLead = trigger.newMap;
    List<Contact> lstContact = new List<Contact>();
    for(Lead objLead: mapNewLead.values())
    {
       if (objLead.isConverted == true) 
       {
         lstContact.add(new contact(LastName = objLead.First_Other_Contact_Name__c));
         lstContact.add(new contact(Phone = objLead.First_Other_Contact_Phone__c));
         lstContact.add(new contact(Email = objLead.First_Other_Contact_Email__c));
       }
    }
    insert lstContact;
}

 
I created a custom object budget and create a lookup relationship with opportunity. So one budget lookup field on opportunity and update this field according to close date via trigger. If close date within month of Jan so budget field update as “Jan”. So all Jan close date opportunity come under Jan budget.
 
My requirement is when any opportunity stage change as close won so opportunities amount should be some and populate on custom field “won amount “ on budget object. Same with open opportunities all open opportunities amount should show on “pipeline amount” custom field.   
I think trigger would be good approach but I don’t know how to query. Could you experts help me?
User-added image
Hi, I created a custom object budget which will store company budget for every month. i created opportunity related list into budget and I want to show all opportunities into that related list according to close date.
Let say if any opportunity close date is Jan so it should be show under Jan budget.
How can I achieve this do I need to create trigger to pull all opportunities into budget related list.

Please suggest.

I am wondering if I have to query other stages with prospecting so how I wrote below soql query:1
String query = 'Select Id, Name, Stage_change_reminder_count__c,StageName From Opportunity WHERE StageName = \'Prospecting\', \'Value Proposition\', \'Process Review\',\’ Validation\' and Open_Tasks__c=0 and Last_Activity_Age__c >=12 ';
But it’s not working why? cann any one help me please.
 
Hi,
I have created a Visual force email template related to opportunity. I want to show last 2 activities realted to opportunity in this email template.
I used <apex:repet rows="4" and it is showing 4 record but accending order. I want to show last activity first then second last activity.

here is my code:

<messaging:emailTemplate subject="Stage  change reminder" recipientType="User" relatedToType="Opportunity">
 <messaging:htmlEmailBody >
  <html>
    <body>
        <h1 style="font-size:100%">
        <p>Dear {!recipient.name},</p></h1>
      
        <p>FYI, appended below is a snapshot of the last few activities related to this opportunity:</p>
            <table border="3" style="width:100%">
             
                <tr>
                    <th>View Activity</th>
                    <th>ActivityDate</th>
                    <th>Subject</th>
                    <th>Status</th>
                </tr>
          
                <apex:repeat rows="2" var="cx" value="{!relatedTo.ActivityHistories}">
                <tr>
                    <td><a href = "https://ap2.salesforce.com/{!cx.id}">View</a></td>
                    <td>{!cx.ActivityDate}</td>
                    <td>{!cx.Subject}</td>
                    <td>{!cx.Status}</td>
                </tr>
                </apex:repeat>
            </table>
            
            <p> Thank You</p>
            <p> Salesforce Team </p>
           
    </body>

  </html>
 </messaging:htmlEmailBody>
</messaging:emailTemplate>

Plz help me to show only last 4 activities in decending order.