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

Announcements

News and Announcements icon
Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

lookup field data on account entity

(0) ShareShare
ReportReport
Posted on by 775

 I will created 3 entities city,state,country  this entities contain default field except city[name* , new_State(fieldtype=lookup), new_country(fieldtype=lookup)]. Then i will create new custom field on account entity is  new_city,new_state,new_country. The main work is when i type in city field =jaypur then when i save the records in the state field=Rajsthan and in the country field=India will automatically written. what should i do , plz give me a related code for that problem

*This post is locked for comments

I have the same question (0)
  • Verified answer
    Aric Levin - MVP Profile Picture
    30,190 Moderator on at

    As far as your entities go, you should make sure of the following:

    Your City Entity, should contain a lookup to the State Entity

    Your State Entity, should contain a lookup to the Country Entity.

    This means that when your users select the city and click on state, only the available state will appear there. After the state is selected, only the country of that state will appear there.

    In order for this to work, you need to set the Related Records Filtering of the State and Country lookup controls on your form:

    In the State field, click on Change Properties, and on the Display Tab in the Related Records Filtering click on Only Show records where, and select City (Accounts) contains City (State).

    Follow the same logic for country field.

    If you need to do this dynamically, you probably need to use webapi.

    You can use the following webapi library and add it as a web resource to your solution and account form:

    www.zacrmguy.com/js-crud-operations-with-web-api-in-crm-2016

    The following is just sample code on how you can achieve that. You will need to modify it as needed, but it should work.

    In the cityOnChangeEvent

    var cityId = removeBraces(getLookupId("new_cityid"));

    getStateId(cityId);

    function getStateId(cityId)

    {

       var query = "_newstateid_value";

       Sdk.WebApi.retrieveRecord(cityId, "new_city", query, "",

       function (result) {

           var stateId = result._newstateid_value;

           retrieveState(stateid);

       },

       function (error) {

           alert(error);

       })

    }

    function retrieveState(stateId)

    {

       var query = "new_stateid,new_statename,_newcountryid_value";

       Sdk.WebApi.retrieveRecord(stateId, "new_state", query, "",

       function (result) {

           var stateName = result.new_statename;

           setLookupField("new_stateid", stateId, stateName, "new_state");

           var countryId = result._newcountryid_value;

           retrieveCountry(countryid);

       },

       function (error) {

           alert(error);

       })

    }

    function retrieveCountry(countryId)

    {

       var query = "new_countryid,new_countryname,_newcountryid_value";

       Sdk.WebApi.retrieveRecord(stateId, "new_state", query, "",

       function (result) {

           var countryName = result.new_countryname;

           setLookupField("new_countryid", countryId, countryName, "new_country");

       },

       function (error) {

           alert(error);

       })

    }

    function getLookupId(fieldName) {

       var field = Xrm.Page.getAttribute(fieldName);

       if (field != null) {

           var fieldId = field.getValue();

           if (fieldId != null)

               return fieldId[0].id.toString();

           else

               return '';

       }

    }

    function setLookupField(fieldName, lookupId, lookupName, entityName) {

       var lookupData = new Array();

       var lookupItem = new Object();

       lookupItem.id = lookupId;

       lookupItem.name = lookupName;

       lookupItem.entityType = entityName;

       lookupData[0] = lookupItem;

       Xrm.Page.getAttribute(fieldName).setValue(lookupData);

    }

    function removeBraces(str) {

       str = str.replace(/[{}]/g, "");

       return str;

    }

  • Verified answer
    kiran_rajput Profile Picture
    775 on at

    thanx Aric,

    but how i take lookup field in plugin for relating city entity to account entity , like all look up values displaying in account entity  

  • Aric Levin - MVP Profile Picture
    30,190 Moderator on at

    I am not sure I follow your question. What do you mean take looking field in plugin. What do you need a plugin for? This all happens on the client, not on the server.

  • Verified answer
    kiran_rajput Profile Picture
    775 on at

    for plugin

    i use this code for lookup field new_citieses to get data from (entity "new_city" ) and entity "new_city" contain 3 fields ("new_city", "new_iistate", "new_iicountry") and "new_iistate"-> lookup->entity("new_state" it contain two fields "new_name"->single line of text and "new_countries"->lookup->new_country) and also new_country is  entity.

    so problem is that when I select jaypur on account entity then save then the lookup field new_istate(rajsthan) and new_icountry(india) set automatically

    code: -

    if (entity.Attributes.Contains("new_citieses") == true && entity.Attributes["new_citieses"] != null)

                           {

                               Guid cityid = ((EntityReference)entity.Attributes["new_city"]).Id;

                               QueryExpression objQuery = (QueryExpression)context.InputParameters["new_city"];

                               ConditionExpression condition1 = new ConditionExpression();

                               condition1.AttributeName = "new_iistate";

                               condition1.Operator = ConditionOperator.Equal;

                               condition1.Values.Add("Maharashtra");

                              /* objQuery.Criteria.AddCondition(condition1);

                               condition1.AttributeName = "new_iicountry";

                               condition1.Operator = ConditionOperator.Equal;

                               condition1.Values.Add("India");

                               objQuery.Criteria.AddCondition(condition1);

                             */

                               FilterExpression filter1 = new FilterExpression();

                               filter1.Conditions.Add(condition1);

                             //QueryExpression query = new QueryExpression("account");

                               objQuery.ColumnSet.AddColumns("new_istate", "new_icountry");

                               objQuery.Criteria.AddFilter(filter1);

                               EntityCollection result1 = service.RetrieveMultiple(objQuery);

    }

    }

    so plz suggest appropriate code for that problem,

    thanx

  • Suggested answer
    Aric Levin - MVP Profile Picture
    30,190 Moderator on at

    Hi Kiran,

    As I mentioned earlier, why do you want to use a plugin?

    WebApi would allow you to bring the values of data before you are savings the record.

    If you decide to use the plugin route, the logic is as follows:

    In your plugin code, get the id of the city record. Either using Target Input Parameter, or calling the Retrieve method of your current entity record

    Call the retrieve method on the city entity, to get the stated:

    Entity city = service.Retrieve("new_city", cityId", "new_stateid");

    Guid stateId = ((EntityReference)(city["new_stateid"])).Id;

    Call the retrieve method on the state entity to get the countryid

    // Use the same logic as above, but retrieve country id from state Entity

    Call the update method on your custom entity, and pass the ids of the state and country

    Entity myEntity = new Entity("new_myentity");

    myEntity.Id = myEntityId; // You can get this from the plugin execution context.

    myEntity["new_stateid"] = new EntityReference(stateEntityName, stateId);

    myEntity["new_countryid"] = new EntityReference(countryEntityName, countryId);

    // Inside Try..Catch

    service.Update(myEntity);

    That should be it. You should be able to figure it out.

    I still recommend api route, but if this is what you are comfortable with, that's ok too.

    Good luck.

  • Verified answer
    kiran_rajput Profile Picture
    775 on at

    Thank You Aric ,

    now I understand what my mistake..

  • Verified answer
    kiran_rajput Profile Picture
    775 on at

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;
    namespace SampleDemo
    {
    public class PluginLook : IPlugin
    {

    public void Execute(IServiceProvider serviceprovider)
    {


    IPluginExecutionContext context =
    (IPluginExecutionContext)serviceprovider.GetService(typeof(IPluginExecutionContext));
    ITracingService tracingservice = (ITracingService)serviceprovider.GetService(typeof(ITracingService));
    // Get a reference to the Organization service.
    IOrganizationServiceFactory factory =
    (IOrganizationServiceFactory)serviceprovider.GetService(typeof(IOrganizationServiceFactory));
    IOrganizationService service = factory.CreateOrganizationService(context.UserId);


    if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
    {
    Entity entity = (Entity)context.InputParameters["Target"];

    if (entity.LogicalName == "account")
    {
    try
    {
    if (entity.Attributes.Contains("new_city") == true && entity.Attributes["new_city"] != null)
    {
    Guid guidcities = ((EntityReference)entity.Attributes["new_city"]).Id;
    ConditionExpression conditionQE = new ConditionExpression();
    conditionQE.AttributeName = "new_state";
    conditionQE.Operator = ConditionOperator.Equal;
    // conditionQE.Values.Add();
    FilterExpression filtercity = new FilterExpression();
    filtercity.Conditions.Add(conditionQE);

    QueryExpression queryexpression = new QueryExpression("account");
    //queryexpression.EntityName = "account";
    queryexpression.ColumnSet = new ColumnSet("new_city","new_state","new_country");
    queryexpression.Criteria.AddFilter(filtercity);
    EntityReference reflook = (EntityReference)entity["new_city"];
    entity = service.Retrieve(entity.LogicalName, guidcities, new ColumnSet(true));
    //EntityCollection record = service.RetrieveMultiple(queryexpression);
    service.Update(entity);

    }
    }
    catch (Exception ex)
    {
    throw new InvalidPluginExecutionException(ex.Message);
    }

    }
    }
    }
    }

    }
    4278.pic.PNG

    i will autopopulate data on state and country field 

  • Verified answer
    Aric Levin - MVP Profile Picture
    30,190 Moderator on at

    So the first question, is does your city entity contain both the state and the country fields. If it doesn't then please follow the solution that I answered in previous post.

    If it does, then in your code after the following line:

    if (entity.Attributes.Contains("new_city") == true && entity.Attributes["new_city"] != null)

    change your code as follows:

    {

    Guid guidcities = ((EntityReference)entity.Attributes["new_city"]).Id;

    // Since you are querying the city entity, you don't need to call a RetrieveMultiple:

    ColumnSet columns = new Columnset("new_stateid", "new_countryid");

    Entity city = service.Retrieve("new_city", cityId", columns);

    Guid stateId = ((EntityReference)(city["new_stateid"])).Id;

    Guid countryId = ((EntityReference)(city["new_countryid"])).Id;

    Entity account = new Entity("account");

    account.Id = context.PrimaryEntityId ; // You can get this from the plugin execution context.

    // Note that you must have entities called state and country for this

    account["new_stateid"] = new EntityReference(stateEntityName, stateId);

    account["new_countryid"] = new EntityReference(countryEntityName, countryId);

    // Inside Try..Catch

    service.Update(account);

    // Comment

    If you do not have a State and County entities, and store the State and Country as text field in the city entity, they must be text fields in the account entity as well. In that case your code will change as follows:

    string stateName = city.Contains("new_state") ?  city["new_state"].ToString() : string.Empty;

    string countryName = city.Contains("new_country") ? city["new_country"].ToString() : string.Empty;

    ...

    account["new_state"] = stateName;

    account["new_country"] = countryName;

    Good luck.

  • Aric Levin - MVP Profile Picture
    30,190 Moderator on at

    Also, if you get an error as above, click and download log file, and paste the log files in here, so that we can see what the exact error is. Thanks.

  • Verified answer
    kiran_rajput Profile Picture
    775 on at

    yes i am getting error again

    Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: The action is not working.Detail:

    <OrganizationServiceFault xmlns:i="www.w3.org/.../XMLSchema-instance&quot; xmlns="schemas.microsoft.com/.../Contracts&quot;>

     <ActivityId>e62e56a1-4f0d-43b6-8747-0cc4120d8585</ActivityId>

     <ErrorCode>-2147220891</ErrorCode>

     <ErrorDetails xmlns:d2p1="schemas.datacontract.org/.../System.Collections.Generic&quot;>

       <KeyValuePairOfstringanyType>

         <d2p1:key>OperationStatus</d2p1:key>

         <d2p1:value xmlns:d4p1="www.w3.org/.../XMLSchema&quot; i:type="d4p1:string">0</d2p1:value>

       </KeyValuePairOfstringanyType>

       <KeyValuePairOfstringanyType>

         <d2p1:key>SubErrorCode</d2p1:key>

         <d2p1:value xmlns:d4p1="www.w3.org/.../XMLSchema&quot; i:type="d4p1:string">-2146233088</d2p1:value>

       </KeyValuePairOfstringanyType>

     </ErrorDetails>

     <Message>The action is not working.</Message>

     <Timestamp>2017-08-28T05:35:49.3822728Z</Timestamp>

     <ExceptionRetriable>false</ExceptionRetriable>

     <ExceptionSource i:nil="true" />

     <InnerFault i:nil="true" />

     <OriginalException i:nil="true" />

     <TraceText>

    [OperationPlugin: OperationPlugin.CreateOpPlugin]

    [522f7050-da88-e711-8125-c4346bdc3c21: OperationPlugin.CreateOpPlugin: Create of account]

    </TraceText>

    </OrganizationServiceFault>

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

Season of Sharing Community Challenge Launch!

Jump in, show your community spirit, and win prizes!

Meet the Microsoft Dynamics 365 Contact Center Champions

We are thrilled to have these Champions in our Community!

Congratulations to the April Top 10 Community Leaders

These are the community rock stars!

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
ScottDurow Profile Picture

ScottDurow 2

#2
GJones Profile Picture

GJones 1

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans