Copy a record

WRITTEN BY Patrick Verbeeten - 30 April 2010

For some records it can be very usefull to copy it. This avoids repetive entry of the same data. If you have a relation on the entity which references itself you can do this using a mapping. But if you do not have a relation and do not whish to create on you can copy the values using the following sample.

First of you need to add an ISV button to the form of the entity you want to copy:

 <Entities>
     <Entity name="new_entity">
       <ToolBar ValidForCreate="0" ValidForUpdate="1">
         <Button Icon="/_imgs/htmlbar/cmd-copy.gif" Client="Web" JavaScript="openObj(crmForm.ObjectTypeCode, null, '_CreateFromId=' + crmForm.ObjectId);">
           <Titles>
             <Title LCID="1033" Text="Copy" />
           </Titles>
         </Button>
       ...

The you need to add the script below to the onload.

var m = location.search.match(/_CreateFromId=(\{[0-9A-F-]+\})/i);
 if (m != null && !location.search.match(/_CreateFromType=/i)) {
     var copyId = m[1];
     var value = null;
     try {
         value= CrmServiceHelper.Retrieve('new_entity', copyId, ['attribute1', 'attribute2', 'attribute3' ]);
     }
     catch (e) { }
 
    if value!= null) {
         //One on one copy (eg for string)
         if (value.attributes['attribute1'] != null) { 
             crmForm.all.attribute1.DataValue = value.attributes['attribute1'].value; 
         }
         //Numeric values
         if (value.attributes['attribute2'] != null) { 
             crmForm.all.attribute2.DataValue = parseFloat(attr.attributes['attribute2'].value); 
         }
         //Lookups
         if (value.attributes['attribute3'] != null) {
             var o = new Object();
             o.typename = 'entitytype';
             o.name = value.attributes['attribute3'].name;
             o.id = value.attributes['attribute3'].value;
             var a = new Array();
             a[0] = o;
             crmForm.all.attribute3.DataValue = a;
         }
     }
 } 

In this script you must modified the retrieve call to retrieve the correct entity type and attributes. The mapping itself must also be build manually the script above contains some samples on how to set most types of fields. To build the simple mappings for string, float and int fields I usually use and excel sheet to quickly build the statements.

This sample uses Daniel Cai's Javascript Web Service Toolkit


Add Comment