Dynamically inserting the results from Dynamic SOQL

This is the 3rd post in a series discussing some complex code we’ve written for recent projects. Our first post detailed performing a query using Dynamic SOQL. Our second post detailed using the Describe method to compile a string of fields used in the Dynamic SOQL query. This third post demonstrates how to reinsert the results of the query.

The actual use case involved a custom clone/archive function that copied a new lead to a custom object. When copying from one object to another you have to ensure that all custom fields have the same API Name and then manually set any standard fields. To simplify the code, this example will copy a contact to a new contact.

//Function to clone existing Contact with dynamic APEX
public static void copyContact()
{
//Create a map from the results of a Describe of the Contact Object
Map<String, Schema.SObjectField> cFieldMap = Schema.SObjectType.Contact.fields.getMap();

//Generate a comma delimited String of Contact Fields
String conFields = '';
for ( String f : cFieldMap.keySet() )
{
	conFields += f;
	conFields += ',';
}
conFields = conFields.subString(0,conFields.Length() -1);

//Define a Where clause
String whereClause = 'WHERE Lastname != null ';

//Define an Order By clause to sort your query
String orderBy = ' Order By MailingState ';

//Define your entire Query as a string
String qryString = 'SELECT ' + conFields + ' FROM Contact ' + whereClause + orderBy + ' limit 1';

//Query salesforce with your Query string
List<Contact> queryResults = Database.query(qryString);

//Create a list of new contacts to insert
List<Contact> contactInserts = new List<Contact>();

for (Contact c : queryResults)
{
	Contact newC = new Contact();
	for ( String f : cFieldMap.keySet() )
	{
		Schema.SObjectField contactField = cFieldMap.get(f);
		Schema.DescribeFieldResult dfr = cFieldMap.get(f).getDescribe();
		if ( c.get(contactField) != null && dfr.isUpdateable() )
		{
			newC.put( cFieldMap.get(f), c.get(contactField) );
		}
	}
	contactInserts.add(newC);
}

insert ContactInserts;
}

Related posts:

  1. Apex Describe with Dynamic SOQl
  2. Dynamic Queries with Apex
  3. Dynamic Picklist Creation and Sorting
  4. New Spring ‘10 feature: SOQL Aggregate Functions
  5. Custom Views on the Home Tab

Post a Comment