web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

How to get current record field value and update it to another field in same entity in plugin

(0) ShareShare
ReportReport
Posted on by 242

How to get current record field value and update it to another field in same entity in plugin

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;

namespace AccountPlugin
{
    public class Class1 : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            //Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                serviceProvider.GetService(typeof(IPluginExecutionContext));
            // Get a reference to the Organization service.
            IOrganizationServiceFactory factory =
                (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));


            IOrganizationServiceFactory servicefactory =
                (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService client = servicefactory.CreateOrganizationService(context.UserId);


            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                // Obtain the target entity from the input parameters.
                Entity entity = (Entity)context.InputParameters["Target"];

                // Verify that the target entity represents an account.
                // If not, this plug-in was not registered correctly.
                if (context.Depth > 1) return;
                if (entity.LogicalName == "account")
                {
                    try
                    {
                        Entity updateaccount = new Entity("account");
                       

                        updateaccount["fax"] = updateaccount.Attributes["telephone1"].ToString();



                       // client.Update(updateaccount);
                    }
                    catch (Exception e)
                    {

                        tracingService.Trace("accountPlugin: {0}", e.ToString());
                        throw;



                    }
                }
                else
                    return;

            }


        }

    }
}


*This post is locked for comments

I have the same question (0)
  • gdas Profile Picture
    50,091 Moderator on at

    Hi,

    Could you please specify little bit details about your requirement .

    What I understand your question you wan to interchange your field value after update right?

    If this is your requirement the write a plugin , define pre-image and post-image in your plugin registration step. Now inside your plugin logic get the value from particular field from pre-image and assign to another field in same record and update the record .

  • madiri Profile Picture
    242 on at

    sure i can explain i have two fields in account one is telephone and fax i need to update telephone value to fax when telephone number updated i dont know how to write code for that i wrote some code please check my code updated now

  • Suggested answer
    Arpit Shrivastava Profile Picture
    7,518 User Group Leader on at

    Hi Madiri,

    It depends on whether the field's value is being modified while creating/updating the record from CRM platform.

    If the value is being modified while creating/updating the record, you can get the current record field's value from Plugin Context.

    But, If the value is not being modified from CRM Platform, then you have two options to retrieve the value:

    Option 1 - Perform query and retrieve the value from the CRM database. Like:

    Entity contactObj = service.Retrieve('contact','new Guid('30dd879c-ee2f-11db-8314-0800200c9a66'), new ColumnSet('firstname')');

    Option 2 - Use Pre-Image. Instead of perform a retrieve query on database, the best practice is to push the required data in an image. 

    Let say: You are writing a plugin on Create of Contact Entity and want to copy emailaddress1 field value to emailaddress2 field. and User is putting the value in emailaddress1 field then Below is the pseudo code of the same.

    // Obtain the execution context from the service provider.
    IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

    // The InputParameters collection contains all the data passed in the message request.

    if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
    {
    // Obtain the target entity from the input parameters.
    Entity contactEntity= (Entity)context.InputParameters["Target"];

    // Verify that the target entity represents an contact.
    if (entity.LogicalName == "contact")
    {
    if (contactEntity.Attributes.Contains("emailaddress1"))
    {
    // Get the value from Emailaddress1 field, you can only get this value from context, if user has put some value in it.
    String PrimaryEmailAddress = contactEntity["emailaddress1"].ToString();

    // Set the Emailaddress1 value in EmailAddress2 field
    contactEntity["emailaddress2"] = PrimaryEmailAddress;

    //You no need to write service.Update(contact entity); if registering the plugin on Pre-Operation Stage

    }

    }
    }

    And as I said, If the value has not been modified from CRM Platform then you will have to retrieve the value using Pre-Image.

    Check my below article to see the difference between Context and Pre-Images and to use Pre-Images in Plugins:

    http://arpitmscrmhunt.blogspot.in/2018/01/pre-image-and-post-image-in-dynamics-crm.html

    Hope it helps.

    If my answer helped to resolve your issue, kindly verify it by clicking 'Yes'. It would be helpful to the other community members seeking to resolve a similar issue.



    Cheers
    Arpit
    https://arpitmscrmhunt.blogspot.in

  • Suggested answer
    Community Member Profile Picture
    on at

    Hi,

    You can use context id to retrieve current record field value

    Guid recordID = context.PrimaryEntityId;

    use service.retrieve to retrieve columns

    example :

    Entity retrieveEntity=service.Retrieve("account",recordID, new columnset (true));

    //to update

    Entity account=new Entity("account");

    account["accountid"]=recordID;

    account["fieldnamtoupdate"]=retrieveEntity.Attributes["FieldValuetoberetrieved"];

    service.update(account);

    Thanks

  • Suggested answer
    Arpit Shrivastava Profile Picture
    7,518 User Group Leader on at

    To meet your requirement, you can take reference of following code:

    Register a plugin on telephone field update and Pre-Operation stage.

    if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
    {
    // Obtain the target entity from the input parameters.
    Entity accountEntity= (Entity)context.InputParameters["Target"];

    // Verify that the target entity represents an contact.
    if (accountEntity.LogicalName == "account")
    {
    if (accountEntity.Attributes.Contains("telephone1"))
    {
    String telephone = accountEntity["telephone1"].ToString();
    accountEntity["fax"] = telephone;

    }

    }
    }

    If my answer helped to resolve your issue, kindly verify it by clicking 'Yes'. It would be helpful to the other community members seeking to resolve a similar issue.

    Cheers
    Arpit
    https://arpitmscrmhunt.blogspot.in

  • Verified answer
    gdas Profile Picture
    50,091 Moderator on at

    Hi ,

    Try with this   , you need to register this plugin in pre-operation and update message of the account entity.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Client;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Xrm.Sdk.Discovery;
    
    namespace AccountPlugin
    {
        public class UpdateFax : IPlugin
        {
            public void Execute(IServiceProvider serviceProvider)
            {
                //Extract the tracing service for use in debugging sandboxed plug-ins.
                ITracingService tracingService =
                    (ITracingService)serviceProvider.GetService(typeof(ITracingService));
    
                // Obtain the execution context from the service provider.
                IPluginExecutionContext context = (IPluginExecutionContext)
                    serviceProvider.GetService(typeof(IPluginExecutionContext));
                // Get a reference to the Organization service.
                IOrganizationServiceFactory factory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
    
    
                IOrganizationServiceFactory servicefactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService client = servicefactory.CreateOrganizationService(context.UserId);
    
    
                // The InputParameters collection contains all the data passed in the message request.
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    // Obtain the target entity from the input parameters.
                    Entity entity = (Entity)context.InputParameters["Target"];
    
                    // Verify that the target entity represents an account.
                    // If not, this plug-in was not registered correctly.
                    if (context.Depth > 1) return;
                    if (entity.LogicalName == "account")
                    {
                        try
                        {                      
                            string telephone = string.Empty;                     
                            if (entity.Attributes.Contains("telephone1"))
                            {
                                telephone = entity.GetAttributeValue<string>("telephone1");
                            }
                            entity["fax"] = telephone;                       
                        }
                        catch (Exception e)
                        {
                            tracingService.Trace("accountPlugin: {0}", e.ToString());
                            throw new InvalidPluginExecutionException(e.Message);
                        }
                    }
                    else
                        return;
    
                }
    
    
            }
    
        }
    }
  • Suggested answer
    Arpit Shrivastava Profile Picture
    7,518 User Group Leader on at

    Hi Everyone,

    Just wanted to avoid the confusion here and would like to make the things clear:

    Point 1. There is no need here to use Pre, Post Image in order to meet this requirement. If I just wanted to copy the Field1 value to Field2 on an update of Field1 then why would I need to use Pre-Image in this case? Can't we get the Field1 modified value from Plugin Context? So pls correct this thing, everyone.

    Point 2: We no need to perform service.Retrieve query here, as we are already getting Entity from Target. We can retrieve the Entity and it's modified field's values from Plugin Context, there is no need to perform one additional query on the database?

    Point 3: Another point, why would I need to perform one additional Database transaction service.Update(entityObj); in order to update the Fax field value in database? 

    We are making one additional database transaction unusually. Can't we push or update the information (fax field data) in Pre-Operation Stage and can avoid one additional DB transaction? Since we are already initiating Update request from CRM Platform and value has yet to be updated in the database core operation stage. Can't we push the updated information(Fax data) along with that? So pls correct this thing, everyone.

    To avoid unusual performance issues in future, These small things should always keep in mind while working with Plugins/Workflows

    Hope everyone understood.

    Thanks

  • gdas Profile Picture
    50,091 Moderator on at

    Agreed Arpit , you are absolutely right , to avoid confusion in one sentence you need to register the plugin in the pre-operation and just assign the phone value to fax field .

                     if (entity.Attributes.Contains("telephone1"))

                           {

                               telephone = entity.GetAttributeValue<string>("telephone1");

                           }

                       entity["fax"] = telephone;

  • Suggested answer
    RaviKashyap Profile Picture
    55,410 Moderator on at

    Hi Madri,

    You don't need to write plugin code to achieve this requirement, you can create a real time workflow which triggers on create/ update of telephone 1 and then updates the fax with the telephone.

    Hope this helps.

  • madiri Profile Picture
    242 on at

    Thank you Goutam :-)

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans