• Rob Lilley
  • NEWBIE
  • 20 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 7
    Questions
  • 8
    Replies
Hi, I wonder if anyone can help please? I know only enough about Apex to create a trigger and class but not to write the code...
I would the ability to automatically create an Account Record when entering a new Contact. (Account Name based on the Last Name of the Contact). Ideally the Account Name to be in the format "The " & Last_Name_& " Household"

(Please note Accounts renamed to 'Households' & Contacts to 'Persons')

I copied and tried this Trigger:

trigger CreateAccountFromContact on Contact (before insert) {
    //Collect list of contacts being inserted without an account
    List<Contact> needAccounts = new List<Contact>();
    for (Contact c : trigger.new) {
        if (String.isBlank(c.accountid)) {
            needAccounts.add(c);
        }
    }
    
    if (needAccounts.size() > 0) {
        List<Account> newAccounts = new List<Account>();
        Map<String,Contact> contactsByNameKeys = new Map<String,Contact>();
        //Create account for each contact
        for (Contact c : needAccounts) {
            String accountName = c.firstname + ' ' + c.lastname;
            contactsByNameKeys.put(accountName,c);
            Account a = new Account(name=accountName);
            newAccounts.add(a);
        }
        insert newAccounts;
        
        //Collect a new list of deal__c objects for new accounts
        //List<Deal__c> newRecsForAccounts = new List<Deal__c>();
        for (Account a : newAccounts) {
            //Put account ids on contacts
            if (contactsByNameKeys.containsKey(a.Name)) {
                contactsByNameKeys.get(a.Name).accountId = a.Id;
            }
            //Deal__c newRec = new Deal__c(name=a.Name, accountId=a.Id);
        }
        
        //insert newRecsForAccounts;
        
    }
    
With this Class:
@isTest
public with sharing class CreateAccountFromContact_UnitTest {
    @isTest
    public static void runTest(){
        String firstname = 'first';
        String lastname = 'last';
        String email = 'firstlast@test.com';
        
        //Create contact
        Contact c = new Contact(firstname=firstname, lastname=lastname, email=email);
        insert c;
        
        //Verify account
        c = [select id, accountid, firstname, lastname, email from Contact where id =:c.Id][0];
        Account a = [select id, name from Account where id = :c.accountId][0];
        
        system.assertEquals(firstname + ' ' + lastname, a.Name);
    }
}
The Class passes the test ok and trigger is active but when I try to save the Contact record the system issues the message:

Contact Creation
I was hoping not to create the Account first,

Many thanks for any help, Rob 
Hi, I wonder if anyone could point me in the right ditection please? we have a custom object 'Monitoring Report' that is updated from an online form and has been working fine for about a year. Without any changes we are occasionally getting the following error message:

Error Message  
There are simple workflow rules against this object and I have de-activated but the issue still persists. I have no idea what a SLEEPY.CPICKLIST might refer to - any help greatly appriated - thank you, Rob 
Hello, I wonder if anyone could help please?

We have a custom email button on a custom object. We would like to double-check the email before sending to the actual recipient by sending it to a 'fixed' email address which is our organisation (where it can be forwareded after checking).

I wonder if this is possible? The code for the button is below.

Many thanks, Rob  

{!REQUIRESCRIPT("/soap/ajax/22.0/connection.js")} 
var query = "Select ContactId, OpportunityId, IsPrimary From OpportunityContactRole Where OpportunityId='{!Opportunity.Id}' AND IsPrimary=true"; 
var result = sforce.connection.query(query); 
var records = result.getArray("records"); 
var location ="/_ui/core/email/author/EmailAuthor?new_template=1&template_id=00X0Y000000IXbS&p3_lkid={!Match__c.Id}&retURL=/{!Match__c.Id}&rtype=003";; 
var contId =''; 
if (records != '') { 
contId = records[0].ContactId; 

if( contId != '' ){ 
location = location+"&p2_lkid="+contId; 

window.location=location ;
Dear Developers,

I have a custom email button on a custom object that works fine, however I have a couple of questions if anybody could help...?

1 - After clicking on button, user has to then search fro contact in the To field and then select email address - is it possible to add something to the button code (below) that will populate the To field automatically with the email address of the Primary Contact?

2 - Also we may have the need to send each email to a fixed internal email address (for checking) before forwarding on. is it possible to add something to the button code (below) that will allow the email to be sent to a fixed email address?

Many thanks, Rob 


{!REQUIRESCRIPT("/soap/ajax/22.0/connection.js")} 

var query = "Select ContactId, OpportunityId, IsPrimary From OpportunityContactRole Where OpportunityId='{!Opportunity.Id}' AND IsPrimary=true"; 

var result = sforce.connection.query(query); 
var records = result.getArray("records"); 
var location ="/_ui/core/email/author/EmailAuthor?new_template=1&template_id=00X0Y000000IXbm&p3_lkid={!Match__c.Id}&retURL=/{!Match__c.Id}&rtype=003";; 
var contId =''; 
if (records != '') { 
contId = records[0].ContactId; 

if( contId != '' ){ 
location = location+"&p2_lkid="+contId; 

window.location=location ;
Hello, I wonder if anyone could help on this please. Fairly new to the coding on buttons.

I have a custom object 'Match' which is not related to Contacts.  I'm trying to create a custom button that has two functions:
  1. Default the To email address to the value in the Volunteer_Email__c on the Match object
  2. When email is sent update the Volunteer_Email_Sent_Date__c on the Match object to the date sent
The code I currently have is:
location.replace('/email/author/emailauthor.jsp?retURL=/{!Match__c.Id}&p3_lkid={!Match__c.Id}&rtype=003&template_id=00X0Y000000IQvm');

It appears to me with (1) above that I can add parameters to default the 'Additional To' and 'CC' to the value you in Volunteer_Email__c but not the To address. (I think it it is looking for a contact which in this case I do not have).

Many thanks for any advice, Rob 

Hi,

I wonder if anyone could advise as have very limited knowledge of Apex. We use Salesforce to give out grants and mainly built around Accounts and Opportunities (renamed to Requests). We have a button on the request which populates two fields on the request:

Previous Grants (long text, rich text format)  (a listing of the grants previous to this request for an account) eg:
2010-2011  £3,000
2012-2013  £2,500

Previous Grants Total (currency)  - the total of all the grant amounts for this account previous to this request.

This all work well. In addition I would now last to have an extra fields that shows just the last grant. Eg 2012-2013  £2,500

Is this possible? I guess it would be in the Select statement somewhere? I have copied the code below.

Many thanks for any help in advance, Rob

global class PopulatePreviousGrantsController {
   
    webService static String populatePreviousGrants(Id oppId) {
       try {
          
            List<String> args = new String[]{'0','number','###,###,##0.00'};
            List<Opportunity> currentOppList=[SELECT Id,Decision_Date__c,AccountId FROM Opportunity WHERE Id= :oppId ];
            List<Opportunity> oppList=[SELECT Id,Grant_Payment_Period__c,Grant_Amount__c,Previous_Grants_Total__c,Decision_Date__c,CreatedDate FROM Opportunity WHERE AccountId = :currentOppList.get(0).AccountId AND Decision_Date__c <= :currentOppList.get(0).Decision_Date__c ORDER BY Decision_Date__c];
            String previousGrants='';
            Decimal previousGrantsTotal=0;
            if(oppList != NULL && oppList.size() > 0) {
           
                for(Opportunity opp :oppList) {
                   
                    if(opp.Grant_Amount__c > 0 && opp.Id != oppId) {
                   
                        String period=opp.Grant_Payment_Period__c == NULL ? '' :opp.Grant_Payment_Period__c;
                        previousGrants+=period+'&nbsp;&nbsp;&nbsp;&pound;'+String.format(opp.Grant_Amount__c.format(), args)+'<br>';
                        previousGrantsTotal+=opp.Grant_Amount__c;
                    }
                }
            }
            Opportunity opp=new Opportunity();
            opp.Id=oppId;
            opp.Previous_Grants__c=previousGrants;
            opp.Previous_Grants_Total__c=previousGrantsTotal;
            update opp;
            return 'Success'; 
        }catch(Exception e) {
       
            System.debug('<--------------ERROR LOG------------------>'+e);
            return e.getMessage();
        }    
    }
}

Hi,
 
I wonder if someone could help please. I know very little about APEX…I probably need a developer but trying this first.

We use Salesforce for giving out grants – the main part being Organisations & Opportunities (Accounts renamed to Organisations and Opportunities renamed to Grant Requests). Opportunities have two custom fields: Grant Amount and a Decision Date. EG £5,000 12/07/2005

Organisations can apply every year and the Apex code we have had written, lists in a rich text field on the latest grant request the previous grants (ie previous to this grant on the same account) and updates a currency field named: Total of Previous Grants. Eg:
 
£2,500  2004-2005
£1,500  2010-2011
£3,400  2014-2015
 
Total of Previous Grants: £7,400
 
As far as I can tell the code is triggered in two ways:
When a new Grant Request (Opportunity) is created – Works perfectly
When the “Populate Previous Grants” button on a Grant Request is clicked – this has an issue...
 
 The issue with the button seems to be that if an old grant request is added (we are entering old ones) that it does not picked if the “Populate Previous Grants” is clicked. However if I just clone the new grant request, the old grant is picked up. If I then clear down the lists of previous grants and total, save, and then click the button it works fine, which I find a bit odd.
 
I can therefore reproduce the problem but cannot work out what the issue may be. I have put the code below.

Any pointers/suggestiosn would be helpful, thanks, Rob

Button Code
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/29.0/apex.js")}
var accId="{!Opportunity.AccountId}";
if( accId != null && accId != '') {
var result = sforce.apex.execute("PopulatePreviousGrantsController","populatePreviousGrants",{oppId:"{!Opportunity.Id}"});
if(result=="Success") {
alert("Previous Grants value updated successfully");
}else {
alert(result);
}
location.reload();
} else {
alert('Opportunity must be associated with a Account');
}

Opportunity Trigger
trigger PopulatePreviousGrants on Opportunity (before insert) {

    Set<Id> accIdSet=new Set<Id>();
    Map<Id,List<Opportunity>> oldAccIdAndOppMap=new Map<Id,List<Opportunity>>();
     Map<Id,List<Opportunity>> newAccIdAndOppMap=new Map<Id,List<Opportunity>>();
    List<Opportunity> updateOppList=new List<Opportunity>();
    List<String> args = new String[]{'0','number','###,###,##0.00'};

    
    for(Opportunity opp:Trigger.New) {
        
        accIdSet.add(opp.AccountId);
        if( opp.AccountId != NULL && !newAccIdAndOppMap.containsKey(opp.AccountId)) {
            
            newAccIdAndOppMap.put(opp.AccountId,new List<Opportunity>());
        } 
        newAccIdAndOppMap.get(opp.AccountId).add(opp);
    }
    
    for(Opportunity opp:[SELECT Id,AccountId,Grant_Amount__c,Grant_Payment_Period__c,Previous_Grants_Total__c,Decision_Date__c From Opportunity WHERE AccountId IN :accIdSet ORDER BY Decision_Date__c ]) {
    
        if( opp.AccountId != NULL && !oldAccIdAndOppMap.containsKey(opp.AccountId)) {
            
            oldAccIdAndOppMap.put(opp.AccountId,new List<Opportunity>());
        } 
        oldAccIdAndOppMap.get(opp.AccountId).add(opp);   
    }
    for(Id accId :newAccIdAndOppMap.keySet()) {
        
        for(Opportunity newOpp:newAccIdAndOppMap.get(accId)) {    
            
            if(oldAccIdAndOppMap.containsKey(accId)) {
                
                String previousGrants='';
                Decimal previousGrantsTotal=0;
                for(Opportunity oldOpp:oldAccIdAndOppMap.get(accId)) {
                    
                    if(oldOpp.Grant_Amount__c > 1) {
                        
                        String period=oldOpp.Grant_Payment_Period__c==NULL?'':oldOpp.Grant_Payment_Period__c;
                        previousGrants+=period+'&nbsp;&nbsp;&nbsp;&pound;'+String.format(oldOpp.Grant_Amount__c.format(), args)+'<br>';
                        previousGrantsTotal+=oldOpp.Grant_Amount__c;
                    }        
                }
               newOpp.Previous_Grants__c=previousGrants;
               newOpp.Previous_Grants_Total__c=previousGrantsTotal; 
            }
            if(!oldAccIdAndOppMap.containsKey(accId)) {
                
                oldAccIdAndOppMap.put(accId,new List<Opportunity>()); 
                oldAccIdAndOppMap.get(accId).add(newOpp);   
            } else {
            
                List<Opportunity> tempOldOpp=new List<Opportunity>();
                boolean flag=false;
                for(Opportunity oldOpp:oldAccIdAndOppMap.get(accId)) {
                    
                    if(newOpp.Decision_Date__c<oldOpp.Decision_Date__c && flag == false) {
                    
                        tempOldOpp.add(newOpp);
                        flag=true;
                    }  
                     
                    tempOldOpp.add(oldOpp);  
                }
                if(flag==false) {
                     
                    tempOldOpp.add(newOpp);    
                }
                oldAccIdAndOppMap.get(accId).clear();
                oldAccIdAndOppMap.get(accId).addAll(tempOldOpp);
                System.debug('<--------------------------------->'+tempOldOpp.size());
            }
            
        }
    }    
}
 

Hi, I wonder if anyone can help please? I know only enough about Apex to create a trigger and class but not to write the code...
I would the ability to automatically create an Account Record when entering a new Contact. (Account Name based on the Last Name of the Contact). Ideally the Account Name to be in the format "The " & Last_Name_& " Household"

(Please note Accounts renamed to 'Households' & Contacts to 'Persons')

I copied and tried this Trigger:

trigger CreateAccountFromContact on Contact (before insert) {
    //Collect list of contacts being inserted without an account
    List<Contact> needAccounts = new List<Contact>();
    for (Contact c : trigger.new) {
        if (String.isBlank(c.accountid)) {
            needAccounts.add(c);
        }
    }
    
    if (needAccounts.size() > 0) {
        List<Account> newAccounts = new List<Account>();
        Map<String,Contact> contactsByNameKeys = new Map<String,Contact>();
        //Create account for each contact
        for (Contact c : needAccounts) {
            String accountName = c.firstname + ' ' + c.lastname;
            contactsByNameKeys.put(accountName,c);
            Account a = new Account(name=accountName);
            newAccounts.add(a);
        }
        insert newAccounts;
        
        //Collect a new list of deal__c objects for new accounts
        //List<Deal__c> newRecsForAccounts = new List<Deal__c>();
        for (Account a : newAccounts) {
            //Put account ids on contacts
            if (contactsByNameKeys.containsKey(a.Name)) {
                contactsByNameKeys.get(a.Name).accountId = a.Id;
            }
            //Deal__c newRec = new Deal__c(name=a.Name, accountId=a.Id);
        }
        
        //insert newRecsForAccounts;
        
    }
    
With this Class:
@isTest
public with sharing class CreateAccountFromContact_UnitTest {
    @isTest
    public static void runTest(){
        String firstname = 'first';
        String lastname = 'last';
        String email = 'firstlast@test.com';
        
        //Create contact
        Contact c = new Contact(firstname=firstname, lastname=lastname, email=email);
        insert c;
        
        //Verify account
        c = [select id, accountid, firstname, lastname, email from Contact where id =:c.Id][0];
        Account a = [select id, name from Account where id = :c.accountId][0];
        
        system.assertEquals(firstname + ' ' + lastname, a.Name);
    }
}
The Class passes the test ok and trigger is active but when I try to save the Contact record the system issues the message:

Contact Creation
I was hoping not to create the Account first,

Many thanks for any help, Rob 
Hello, I wonder if anyone could help on this please. Fairly new to the coding on buttons.

I have a custom object 'Match' which is not related to Contacts.  I'm trying to create a custom button that has two functions:
  1. Default the To email address to the value in the Volunteer_Email__c on the Match object
  2. When email is sent update the Volunteer_Email_Sent_Date__c on the Match object to the date sent
The code I currently have is:
location.replace('/email/author/emailauthor.jsp?retURL=/{!Match__c.Id}&p3_lkid={!Match__c.Id}&rtype=003&template_id=00X0Y000000IQvm');

It appears to me with (1) above that I can add parameters to default the 'Additional To' and 'CC' to the value you in Volunteer_Email__c but not the To address. (I think it it is looking for a contact which in this case I do not have).

Many thanks for any advice, Rob 

Hi,
 
I wonder if someone could help please. I know very little about APEX…I probably need a developer but trying this first.

We use Salesforce for giving out grants – the main part being Organisations & Opportunities (Accounts renamed to Organisations and Opportunities renamed to Grant Requests). Opportunities have two custom fields: Grant Amount and a Decision Date. EG £5,000 12/07/2005

Organisations can apply every year and the Apex code we have had written, lists in a rich text field on the latest grant request the previous grants (ie previous to this grant on the same account) and updates a currency field named: Total of Previous Grants. Eg:
 
£2,500  2004-2005
£1,500  2010-2011
£3,400  2014-2015
 
Total of Previous Grants: £7,400
 
As far as I can tell the code is triggered in two ways:
When a new Grant Request (Opportunity) is created – Works perfectly
When the “Populate Previous Grants” button on a Grant Request is clicked – this has an issue...
 
 The issue with the button seems to be that if an old grant request is added (we are entering old ones) that it does not picked if the “Populate Previous Grants” is clicked. However if I just clone the new grant request, the old grant is picked up. If I then clear down the lists of previous grants and total, save, and then click the button it works fine, which I find a bit odd.
 
I can therefore reproduce the problem but cannot work out what the issue may be. I have put the code below.

Any pointers/suggestiosn would be helpful, thanks, Rob

Button Code
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/29.0/apex.js")}
var accId="{!Opportunity.AccountId}";
if( accId != null && accId != '') {
var result = sforce.apex.execute("PopulatePreviousGrantsController","populatePreviousGrants",{oppId:"{!Opportunity.Id}"});
if(result=="Success") {
alert("Previous Grants value updated successfully");
}else {
alert(result);
}
location.reload();
} else {
alert('Opportunity must be associated with a Account');
}

Opportunity Trigger
trigger PopulatePreviousGrants on Opportunity (before insert) {

    Set<Id> accIdSet=new Set<Id>();
    Map<Id,List<Opportunity>> oldAccIdAndOppMap=new Map<Id,List<Opportunity>>();
     Map<Id,List<Opportunity>> newAccIdAndOppMap=new Map<Id,List<Opportunity>>();
    List<Opportunity> updateOppList=new List<Opportunity>();
    List<String> args = new String[]{'0','number','###,###,##0.00'};

    
    for(Opportunity opp:Trigger.New) {
        
        accIdSet.add(opp.AccountId);
        if( opp.AccountId != NULL && !newAccIdAndOppMap.containsKey(opp.AccountId)) {
            
            newAccIdAndOppMap.put(opp.AccountId,new List<Opportunity>());
        } 
        newAccIdAndOppMap.get(opp.AccountId).add(opp);
    }
    
    for(Opportunity opp:[SELECT Id,AccountId,Grant_Amount__c,Grant_Payment_Period__c,Previous_Grants_Total__c,Decision_Date__c From Opportunity WHERE AccountId IN :accIdSet ORDER BY Decision_Date__c ]) {
    
        if( opp.AccountId != NULL && !oldAccIdAndOppMap.containsKey(opp.AccountId)) {
            
            oldAccIdAndOppMap.put(opp.AccountId,new List<Opportunity>());
        } 
        oldAccIdAndOppMap.get(opp.AccountId).add(opp);   
    }
    for(Id accId :newAccIdAndOppMap.keySet()) {
        
        for(Opportunity newOpp:newAccIdAndOppMap.get(accId)) {    
            
            if(oldAccIdAndOppMap.containsKey(accId)) {
                
                String previousGrants='';
                Decimal previousGrantsTotal=0;
                for(Opportunity oldOpp:oldAccIdAndOppMap.get(accId)) {
                    
                    if(oldOpp.Grant_Amount__c > 1) {
                        
                        String period=oldOpp.Grant_Payment_Period__c==NULL?'':oldOpp.Grant_Payment_Period__c;
                        previousGrants+=period+'&nbsp;&nbsp;&nbsp;&pound;'+String.format(oldOpp.Grant_Amount__c.format(), args)+'<br>';
                        previousGrantsTotal+=oldOpp.Grant_Amount__c;
                    }        
                }
               newOpp.Previous_Grants__c=previousGrants;
               newOpp.Previous_Grants_Total__c=previousGrantsTotal; 
            }
            if(!oldAccIdAndOppMap.containsKey(accId)) {
                
                oldAccIdAndOppMap.put(accId,new List<Opportunity>()); 
                oldAccIdAndOppMap.get(accId).add(newOpp);   
            } else {
            
                List<Opportunity> tempOldOpp=new List<Opportunity>();
                boolean flag=false;
                for(Opportunity oldOpp:oldAccIdAndOppMap.get(accId)) {
                    
                    if(newOpp.Decision_Date__c<oldOpp.Decision_Date__c && flag == false) {
                    
                        tempOldOpp.add(newOpp);
                        flag=true;
                    }  
                     
                    tempOldOpp.add(oldOpp);  
                }
                if(flag==false) {
                     
                    tempOldOpp.add(newOpp);    
                }
                oldAccIdAndOppMap.get(accId).clear();
                oldAccIdAndOppMap.get(accId).addAll(tempOldOpp);
                System.debug('<--------------------------------->'+tempOldOpp.size());
            }
            
        }
    }    
}