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..

5 comments:

  1. Congratulation,for the post.This is a very costly present.I am so satisfied to get this
    post article.I was anticipating get such a post which is exceptionally useful to us.
    Keep it up. .I know something data, to know you can click here
    Zutrittskontrolle Gesundheit
    Zutrittssysteme Verein

    ReplyDelete
  2. I found your blog when I was looking for a different sort of information
    but I was very happy and glad to read through your blog. The information
    available here is great. . I know something information, to know you can click here
    Shoes
    shoewebster

    ReplyDelete
  3. Nice request InitializeFromRequest, I can think of so many uses for this in some of my plugin code.

    Thanks for sharing!

    ReplyDelete