locked
Plugin for convert one custom entity record to another new custom entity record in ms crm 2011 RRS feed

  • Question

  • There are two  custom entities one is Applicant and other is Student entity.

    Here Applicant record has to be converted into new student record by clicking a custom button in the ribbon.(like converting lead to contact)

    Once Applicant record is converted into Student record , the status of the applicant record should be inactive.

    How to achieve this...  Please help me...

     

     

    Friday, December 2, 2011 7:30 AM

Answers

  • Thnaks for your reply...

     I  created one Ondemand workflow and it works fine..

    Thank you..

     

    Friday, December 2, 2011 11:57 AM

All replies

  • I have one req,

    There are two  custom entities one is Applicant and other is Student entity.

    Here Applicant record has to be converted into new student record by clicking a custom button in the ribbon.

    Once Applicant record is converted into Student record , the status of the applicant record should be inactive.

    How to achieve this...  

     

    Friday, December 2, 2011 4:55 AM
  • You have to use either REST or SOAP. 

    On Ribbon button click call JavaScript function which will read attributes on Applicant form and create Student entity record. Once Student entity record is created have SetStateRequest to make Applicant inactive. 

    You have one more option as have check box on Applicant form and when Check box is checked by user and Applicant is saved, either have Workflow or Plugin to create Student out of Applicant. 


    MaKeer | myencounterwithcrm.wordpress.com | CRM2011 User Settings Utility | CRM2011 Lookup Preview | CRM2011 Lookup Attribute Mapping | CRM2011 TreeView Control (Beta)
    Friday, December 2, 2011 5:07 AM
  • Hi Shetty,

    There are a few ways to archive your requirements.

    One method is to create a workflow using the "Application" entity as your starting point. In the workflow you would add the "Create Record" step and create a new "Student" entity record, then add another step to deactivate the "application" record.

    Set the workflow "As an on-demand process" and remove all check against "Start when:"

    You can trigger the workflow the normal way or here is a link that shows you how to create a custom button and trigger the workflow.

    http://andreaswijayablog.blogspot.com/2011/07/crm-2011-custom-button-on-custom-entity.html

    Hope this helps.


    Eric UNG [Senior Analyst Programmer :: Sydney, Australia]
    Friday, December 2, 2011 5:12 AM
  • Hi Shetty,

    I guess there are multiple ways to achieve this. Since you have mentioned about having a Button on Ribbon to convert Applicant to Student. 

     

    1) I believe you can do the whole process in Jscript.

    2) Combination of Jscript + Plugin

    3) Synchronous (On-demand) workflow

     

    I am not much confident with step 1st, we will discuss step2 and step 3

     

    Now to achieve Step2 and Step3, you need to add a picklist, having two or three values such as New, Converted and Cancel.

     

    Also you need to create Plugin which will get registered against Applicant entity on Update message with Pre-Image, and this plugin will have logic to read the attribute values from Applicant entity and 

    define a Student, assign required values from Applicant entity pre-image. Also you can do a validation of the newly created picklist attribute from the Target to make sure the current value is Converted and also you can verify against what was the previous value from Pre-Image.

    to change the status use the following code in the plugin after the creation of Student record.

    SetStateRequest setStateRequest = new SetStateRequest()
                    {
                        EntityMoniker = new EntityReference
                        {
                            Id = applicantId,
                            LogicalName = Applicant.EntityLogicalName,
                        },
                        State = new OptionSetValue((int)ContactState.Inactive),
                        Status = new OptionSetValue(2)
                    };
                    _serviceProxy.Execute(setStateRequest);
    
    

    Using Jscript on the button, you can change the value on this newly created picklist attribute to Converted and force a Save action from Jscript.
    var lcstatus = Xrm.Page.getAttribute("new_lifecyclestatus");
    //set Converted - an example
    lcstatus.setValue(100000000);
    // save now.
     Xrm.Page.data.entity.save();
    
    

    Now this action will trigger the Platform Save action, and the earlier plugin will fire and the Student record will get created.
    You can do the same logic with just the Plugin and new attribute, only problem is user has to manually change the Picklist value to Conveted and then Click on Save will trigger the plugin.
    I guess workflow also similar to above mentioned, you need to build up similar logic as plugin in workflow and new attribute, then the user has to run the workflow manually.
    I think the 2nd step is the best option.
    hope this will help.


    Thomas T(MCBMSS) If you find this post helpful then please "Vote as Helpful" and "Mark As Answer".
    Friday, December 2, 2011 5:25 AM
  • Thanks for reply.. sir..

    You have any plugin for converting one custom entity to new custom entity record.. in ms crm 2011

     

     

    Friday, December 2, 2011 6:11 AM
  • Hi ,

    I have one req, that is

    There are two  custom entities one is Applicant and other is Student entity.

    Here Applicant record has to be converted into new student record by clicking a custom button in the ribbon.(like converting lead to contact)

    Once Applicant record is converted into Student record , the status of the applicant record should be inactive.

    How to achieve this...  Please help me...

    Friday, December 2, 2011 7:32 AM
  • Hello,

    You can achieve your goal in 2 ways - plugin and JavaScript so you can choose.

    For Plugin approach approximate algorithm is following:

    1. Create custom attribute for the Applicant record and call it converted.

    2. With JavaScript set to value that will mean that record should be converted.

    3. Develop Plugin which will handle update of this attribute, create Student record and set Applicant to inactive.

    JavaScript approach would be the same but you would not need those custom attribute.

     

    UPD: Please don't create duplicated threads. Anyway I will merge it.


    Microsoft CRM Freelancer

    My blog (english)
    Мой блог (русскоязычный)
    Follow Andriy on Twitter
    Friday, December 2, 2011 7:42 AM
    Moderator
  • Hi Shetty,

    There is no one line command to convert one entity to another entity when both entities are different.

    In your case when you register your plugin you must register PreImage step as well, and inside your plugin you read the Applicant values from the registered Pre-Image, assign all the required values to a Student object from the Applicant object, and then you call serviceProxy.Create(student).

    Please refer the following sample plugin which registered against Account entity on Update message. when the user changes RelationShip Type to Customer, it will create a Task and change the Account status to Inactive.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.ServiceModel;
    using System.Text;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Crm.Sdk.Messages;
    
    namespace PluginTest
    {
        public class OnUpdatePluginTest : IPlugin
        {
            /// <summary>
            /// Post-Operation Plugin.
            /// A plug-in that triggers when the Account entity record RelationShip changes.
            /// and creates a follow up Task Record.
            /// </summary>
            /// <remarks>
            /// Register this plug-in: 
            /// Message: Update
            /// Primary Entity: account
            /// Event Pipeline Stage: Pre-Operation
            /// PreImage Name: AccountPreImage
            /// </remarks>
            public void Execute(IServiceProvider serviceProvider)
            {
                try
                {
                    var context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
                        serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));
                    
                    //Extract the tracing service for use in debugging sandboxed plug-ins.
                    ITracingService tracingService =
                        (ITracingService)serviceProvider.GetService(typeof(ITracingService));
    
    
                    // check runtime context.
                    if (context.IsOfflinePlayback)
                    {
                        // This plug-in was fired from the playback queue after the user
                        // selected to go online within Microsoft Dynamics CRM for Outlook.
                        return;
                    }
    
                    if (context.InputParameters.Contains("Target") &&
                        context.InputParameters["Target"] is Entity)
                    {
                        var targetEntity = (Entity)context.InputParameters["Target"];
    
                        //validating the whether the user has updated Target Entity (Account) customertypecode attribute.
                        if (!targetEntity.Attributes.Contains("customertypecode"))
                        {
                            return;
                        }
    
                        string preEntityImageName = "AccountPreImage"; //when you register your must specify this name.
                        if (context.PreEntityImages.Contains(preEntityImageName) == false)
                        {
                            //PreEntityImages collection does not have the AccountPreImage image
                            return;
                        }
    
                        if (context.PreEntityImages[preEntityImageName] == null)
                        {
                            //The value of AccountPreImage in PreEntityImages is null
                            return;
                        }
    
                        // get PreEntity.
                        var preEntity = (Entity)context.PreEntityImages[preEntityImageName];
                        
                        //validate if the RelationShipCode is already a  Customer
                        if (preEntity.GetAttributeValue<OptionSetValue>("customertypecode").Value == 3)
                        {
                            string msg = string.Format("Cannot update this Account, the record Relationship Type is already a Customer.");
                            throw new InvalidPluginExecutionException(msg);
                        }
                        else
                        {
                            //validating what is the value of customertypecode User has chagned to.
                            //If the current customertypecode <> Customer then return
                            if (targetEntity.GetAttributeValue<OptionSetValue>("customertypecode").Value != 3)
                            {
                                return;
                            }
    
    
                            Guid accountId = preEntity.GetAttributeValue<Guid>("accountid");
                            tracingService.Trace(string.Format("OnUpdatePluginTest: AccountId: {0}", accountId));
    
                            Entity followup = new Entity("task");
                            followup["subject"] = string.Format("Send e-mail to {0}.", preEntity.GetAttributeValue<string>("name")); //retrieving Account Name from Pre-Image
                            followup["description"] = "Follow up with the customer. Check if there are any new issues that need resolution.";
                            followup["scheduledstart"] = DateTime.Now.AddDays(7);
                            followup["scheduledend"] = DateTime.Now.AddDays(7);
                            followup["category"] = context.PrimaryEntityName;
                            // Refer to the account in the task activity.
                            if (accountId != Guid.Empty)
                            {
                                Guid regardingobjectid = new Guid(accountId.ToString());
                                string regardingobjectidType = "account";
                                followup["regardingobjectid"] = new EntityReference(regardingobjectidType, regardingobjectid);
                            }
    
                            var factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                            IOrganizationService service = factory.CreateOrganizationService(null);
                            // Create the task in Microsoft Dynamics CRM.
                            Guid newTaskId = service.Create(followup);
                            tracingService.Trace(string.Format("OnUpdatePluginTest: newTaskId: {0}", newTaskId));
                            if (newTaskId != Guid.Empty)
                            {
                                //Update the Status of Account to Inactive.
                                SetStateRequest setStateRequest = new SetStateRequest()
                                {
                                    EntityMoniker = new EntityReference
                                    {
                                        Id = accountId,
                                        LogicalName = "account"
                                    },
                                    State = new OptionSetValue(1), //Inactive
                                    Status = new OptionSetValue(2) //Inactive
                                };
                                service.Execute(setStateRequest);
                                tracingService.Trace(string.Format("OnUpdatePluginTest: setStateRequest"));
                            }
                            else
                            {
                                string msg = string.Format("Error occured while Creating Task when Account RelationShipCode changed to Customer.");
                                throw new InvalidPluginExecutionException(msg);
                            }
    
                        }
                    }
                }
                catch (InvalidPluginExecutionException)
                {
                    throw;
                }
                catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
                {
                    throw new InvalidPluginExecutionException("An FaultException occurred in the OnUpdatePluginTest plug-in.", ex);
                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException("An Exception occurred in the OnUpdatePluginTest plug-in.", ex);
                }
            }
        }
    
    }
    

    register plugin

    register plugin image


    Thomas T(MCBMSS) If you find this post helpful then please "Vote as Helpful" and "Mark As Answer".
    Friday, December 2, 2011 8:31 AM
  • Thanks for reply sir,

    you have any javascript function to read attributes and create new entity record..

     

    Friday, December 2, 2011 9:30 AM
  • Thnaks for your reply...

     I  created one Ondemand workflow and it works fine..

    Thank you..

     

    Friday, December 2, 2011 11:57 AM
  • Hi Eric Thanks for your reply...

    In my req i tried with on demand workflow but the workflow triggers automatically. That is when I create Applicant record and clicked save button and save&close the record is goes to Student entity.

    I need to trigger the workflow when I click the button in the ribbon. How do solve this ....

    Saturday, December 3, 2011 4:52 AM
  • Hello,

    By default when you create workflow Create checkox is checked. It seems that you forgot to uncheck it. So solution for your case is:

    1. Unpublish workflow.

    2. Uncheck Create triggering option.

    3. Recheck that On-Demand checkbox is checked.

    4. Publish workflow


    Microsoft CRM Freelancer

    My blog (english)
    Мой блог (русскоязычный)
    Follow Andriy on Twitter
    Saturday, December 3, 2011 8:42 AM
    Moderator
  • Thank You sir ,

    I got it , and it works fine..

    How can I call the workflow in entity form ribbon with a custom button .When I click that button workflow must trigger...

    how to achieve this ...

    Monday, December 5, 2011 4:15 AM
  • How you have matched Option Set from Work-flow if you have any, WF's can not copy Option Sets from one to another because they are dynamic.

    Let me know. i am interested in your solution, i have created WF's something similar to you, more like Business Data Auditing for 4.0 and Also used the same logic for 2011 for something else. Biggest disadvantage is Option Set can not be matched and copied over through WF's.


    Puneet Joshi - Dynamics CRM Developer

    Wednesday, September 26, 2012 12:54 PM
  • plug in to update a field in one entity when a field in other entity is updated by on save.

    here i have a scenario where a field should be updated automatically when i change a field in other entity by onsave.

    pls show me a plugin to work on this...

    Sunday, January 5, 2014 7:47 AM
  • Laxmi,

    You may not need a plugin for your requirement. It can be achieved via OData using JScript much easier approach than Plugin.

    On change of the field value you can call the Odata using JavaScript. Read the changed value and set that to another entity's field.

    Makes sense.


    Puneet Joshi - Dynamics CRM Developer

    Sunday, January 5, 2014 6:31 PM