Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

So i have two copies of an object and i want to copy over most but not all of the fields from one to the other. Luckily, i use naming conventions to help, all the fields i need to copy over start with Assets or Banking so this is what im playing with

Map<String, Schema.SobjectField> MeetingFields = Schema.SObjectType.Meeting__c.fields.getMap();

for(String key : MeetingFields.keySet()) {

   if (key.startsWith('Assets') || key.startsWith('Banking')  ) {
       meeting[key] = prevMeeting.get(key);
   }

}

the two objects, meeting and prevMeeting are both Meeting__c sObjects..

It does loop through all the fields and key is fine but how do i get the key from each object to do the copy?

I tried

meeting[key] = prevMeeting.get(key);
meeting.get(key) = prevMeeting.get(key);

Is there an easier way to do this?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

See the SObject.put() method.

Map<String, Schema.SobjectField> MeetingFields = Schema.SObjectType.Meeting__c.fields.getMap();

for(String key : MeetingFields.keySet()) {

   if (key.startsWith('Assets') || key.startsWith('Banking')  ) {
       meeting.put(key, prevMeeting.get(key));
   }

}
share|improve this answer
    
Duh! thanks for this. Do you know offhand if the .get() method will get a fields value even if its not in the original query that build the object or will it only get existing field values –  Keith Mancuso Jun 21 at 19:16
1  
No, it won't. You'll get an exception. –  sfdcfox Jun 21 at 19:31
    
Thats what I thought, thanks. –  Keith Mancuso Jun 21 at 21:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.