Monday, November 24, 2014

InitializeFromRequest in CRM2013

InitializeFromRequest may be the least used request in the Dynamics CRM. It is available since CRM 4.0. I was talking to some of the guys in my team and most of them have never used this request. It initiates an instance of an entity from an existing entity.

It can be used when there is a 1:N relationship between the entities. It is equivalent of creating a child record from the parent form.

For example there is a 1:N relationship between account and contact. if you create a contact from the contact subgrid from the account form, it will prefill the parentcustomer field and all the fields defined in the relationship mappings.

The following screen shot displays the mappings of 1:N relationship between account and contact.
image
The same functionality can be achieved using InitializeFromRequest. This request returns a InitializeFromResponse. The request does not create a new record but the response can be used to create a new record.
Here is the code.
    // Create the request object
     InitializeFromRequest initialize = new InitializeFromRequest();

     // Set the properties of the request object
     initialize.TargetEntityName = "contact";
     

     // Create the EntityMoniker
     initialize.EntityMoniker = new EntityReference("account", new Guid("8A5D8108-DE3B-E311-9401-00155D1B7B00"));
    
     // fields to initialised from parent entity
     initialize.TargetFieldType = TargetFieldType.All;

     // Execute the request
     InitializeFromResponse initialized =
         (InitializeFromResponse)_serviceProxy.Execute(initialize);

     if (initialized.Entity != null)
     {
         //get entity from the response
         Entity entity = initialized.Entity;

         // set the name for the contact
         entity.Attributes.Add("firstname", "John");
         entity.Attributes.Add("lastname", "Smith");

         //create a new contact
         _serviceProxy.Create(entity);

     }
        
Happy coding..