This example code will clone the opportunity for each opportunity contact role. It uses the ‘selectwhere’ url parameter to filter the contact roles, and each new opportunity will have a single contact role record.
A Javascript custom button is used with Salesforce Ajax toolkit. The Ajax toolkit queries the OpportunityContactRole object by the opportunity record id. Javascript logic loops through the results to build the url, and then it loads the page for the user. The user is presented with a clone confirmation page that will display the opportunity to clone with each individual contact role record.
The ‘selectwhere’ takes 4 parameters that are delimited by ‘:’. Multiple where conditions can be included by delimiting them by ‘;;’. Including an ‘OR’ condition can be done by adding ‘||’ before the object name in the first parameter. If the object reference or field name is invalid, the logic will ignore the filtering logic, and all records will be included when cloning.
In the example below, the configuration name is ‘MyOppCfg’. Your configuration name can be something else, but you would need to update the script to reflect the different name.
{!REQUIRESCRIPT("/soap/ajax/37.0/connection.js")} var NewUrl = ''; var myquery = "SELECT ContactId, Id, OpportunityId, Role FROM OpportunityContactRole WHERE OpportunityId = '{!Opportunity.Id}'"; var result = sforce.connection.query(myquery); var records = result.getArray("records"); if (0 === records.length) { alert('No Opportunity Contact Role\'s have been found.'); // uncomment this line if you want to simply clone the opportunity when there are no opportunity contact role records // window.location = '/apex/lcrm_scp__scpClone?&rid={!Opportunity.Id}&cfg=MyOppCfg'; } else { for (var i=0; i < records.length; i++) { NewUrl = '/apex/lcrm_scp__scpClone?&rid={!Opportunity.Id}&cfg=MyOppCfg&selectwhere=OpportunityContactRole:ContactId:=:' + records[i].ContactId + (''===NewUrl? '' : '&retURL2='+encodeURIComponent(NewUrl) + '&saveURL2='+encodeURIComponent(NewUrl)); } window.location = NewUrl; }
The URL will look similar to this:
https://lcrm_scp.na16.visual.force.com/apex/scpClone?rid=006j000000Yu2F9&cfg=MyOppCfg&saveURL2=%2Fapex%2Flcrm_scp__scpClone%3F%26rid%3D006j000000Yu2F9%26cfg%3DMyOppCfg%26selectwhere%3DOpportunityContactRole%3AContactId%3A%3D%3A003j000001UM91gAAD&retURL2=%2Fapex%2Flcrm_scp__scpClone%3F%26rid%3D006j000000Yu2F9%26cfg%3DMyOppCfg%26selectwhere%3DOpportunityContactRole%3AContactId%3A%3D%3A003j000001UM91gAAD&selectwhere=OpportunityContactRole%3AContactId%3A%3D%3A003j000001UM91hAAD
The user would click the custom button on the Opportunity page.