I am messing around with the dynamic nature of Salesforce. I want to clone Opportunity into a custom object. It's a very easy requirement in itself. What I am trying to do is make if completely dynamic right down to the fields which I am setting. Yes I could do it with WFR
I want the ability to add/remove fields to be copied into the custom object using field sets.
I have a field set on the opportunity which I am describing out and a field set on my custom object describing that too. Then I am creating a field mapping map between the two which I can then loop over and set an unknown amount of fields.
It doesn't seem to like this line (see below for full code) //c.fieldMapping.get(oppFields[0].getFieldPath()) = o.Name;
I get invalid fieldmapping for sObject. Is this kind of thing possible?
Thanks
public class OpportunityToCampaignDelivery{
static string query = 'select ';
public OpportunityToCampaignDelivery(){}
public void OnAfterUpdate(Opportunity[] oldOpps, Opportunity[] updatedOpps, Map<ID, Opportunity> oppMap){
List<Schema.FieldSetMember> oppFields =
Schema.SObjectType.Opportunity.fieldSets.getMap().get('CD_Fields').getFields();
List<Schema.FieldSetMember> cdFields =
Schema.SObjectType.Campaign_Delivery__c.fieldSets.getMap().get('CD_Fields').getFields();
// Empty map to store standard to custom object field mapping
Map<String, String> fieldMapping = new Map<String, String>();
for (Schema.FieldSetMember f : oppFields){
query += f.getFieldPath() + ', ';
if (f.getFieldPath()!='Name'){
fieldMapping.put(f.getFieldPath(), 'CD_'+ f.getFieldPath()+'__c');
}
else{
fieldMapping.put(f.getFieldPath(), 'Name');
}
}
System.debug('=====DEBUG=====' + 'What is in my map =' + fieldMapping);
// Update query string to remove , from last dynamic field add
string newQuery = query.substring(0,query.length()-2);
// TODO: Add where clause
newQuery += ' from Opportunity';
newQuery += ' where Id in: ' + oppMap.keyset();
// Execute dynamic query
List<Opportunity> opps = Database.query(newQuery);
Map<Id, Opportunity> cdMap = new Map<Id, Opportunity>();
Integer i = 0;
for (Opportunity o:opps){
cdMap.put(o.Id,o);
}
System.debug('=====DEBUG=====' + 'What is in my map =' + cdMap);
List<Campaign_Delivery__c> cdsToInsert = new List<Campaign_Delivery__c>();
for (Opportunity o : [select Id from Opportunity where Id in : cdMap.keyset()]){
Campaign_Delivery__c c = new Campaign_Delivery__c();
String FieldNames = fieldMapping.get(oppFields[0].getFieldPath());
System.debug('=======DEBUG====== my first field name is ' + FieldNames);
//c.fieldMapping.get(oppFields[0].getFieldPath()) = o.Name;
}
}
}