locked
Dynamic Optionset in CRM 2011 RRS feed

  • Question

  • I have a requirement where i have Custom Entity with two Fields name  A and B.  Both the fields are optionset.

    Now on the  A field i want all the entities name  and on the B field  i want all the attributes for that selected entity in field B.

    For Example :

    A field have "Account " as the entity than on Field B all the attributes of entity will be there.

    Please Help !! 

    Friday, February 20, 2015 7:17 AM

All replies

  • Hello,

    You would not be able to do it using OOB Optionsets. The only good way I see is to develop webresource that will fetch CRM metadata and populate dropdowns with requried data. Recheck following sample - https://msdn.microsoft.com/en-us/library/gg594428.aspx


    Dynamics CRM MVP/ Technical Evangelist at SlickData LLC
    My blog

    Friday, February 20, 2015 8:05 AM
    Moderator
  • Can anyone please let me know How can i populate the meta data into dropdowns ?  Is there any way using fetch xml .
    Friday, February 20, 2015 10:49 AM
  • Can anyone please let me know How can i populate the meta data into dropdowns ?  Is there any way using fetch xml .

    I've already provided an url that shows how it could be implemented with JS.

    Fetch Xml works only with Data and not with Metadata.


    Dynamics CRM MVP/ Technical Evangelist at SlickData LLC
    My blog

    Friday, February 20, 2015 11:04 AM
    Moderator
  • http://crmxpg.nl/wp/2010/10/22/display-tooltips-for-fields-in-ms-crm-part-2/

    i need a similar feature as shown in the above link for a CRM 2011 instance. Below is the JS i modified for CRM 2011.

    //*********************************************************
    function initializePicklists()
     {
        
        //retrieve customizable entities build and entity picklist
        var list = gGetEntityList();
        var name = list[0];
        var displayname = list[1];
        gConvertTextToPickList('new_entity', name);

        //retrieve attributes and build attribute picklist
        var entity = Xrm.Page.getAttribute("new_entity").getValue();
        gConvertTextToPickList('new_attribute', gGetAttributeList(entity)[0]);
    }

    //*********************************************************
    function gQueryMetadataService(request)
     {

        /*
        Description:   Generic function to call the metadata webservice
        Calls by :  gGetEntityList() and gGetAttributeList()
        Returns:   XML response array
        Example:
        var request = "<Request xsi:type='RetrieveAllEntitiesRequest'>" +
        "<MetadataItems>EntitiesOnly</MetadataItems>" +  //MetadataItems – The items you wish to retrieve e.g. EntitiesOnly, IncludeAttributes, IncludePrivileges, IncludeRelationships and All.
        "<RetrieveAsIfPublished>false</RetrieveAsIfPublished>" +  //RetrieveAsIfPublished – specifies whether you want to get a list of just the published entity metadata or all of the entity metadata.
        "</Request>";
        var result = gQueryMetadataService(request);
        var logicalNames = result.selectNodes("//CrmMetadata/LogicalName");
        */

         var soapMessage = "<?xml version='1.0' encoding='utf-8'?>" +
     "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
     "xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +

    Xrm.Page.context.getAuthenticationHeader() +

       "<soap:Body><Execute xmlns='http://schemas.microsoft.com/xrm/2011/Contracts/Services' " + request + "</Execute></soap:Body>" +

         "</soap:Envelope>";

        var xmlHttpRequest = new XMLHttpRequest();
        xmlHttpRequest.open("POST", getServerUrl, true)
        // Responses will return XML. It isn't possible to return JSON.
        xmlHttpRequest.setRequestHeader("Accept", "application/xml, text/xml, */*");
        xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
        
        


    //    var soapMessage = "<?xml version='1.0' encoding='utf-8'?>" +
    // "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
    // "xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +
    //    
    //Xrm.Page.context.getAuthenticationHeader() +

    //   "<soap:Body><Execute xmlns='http://schemas.microsoft.com/xrm/2011/Contracts/Services' " + request + "</Execute></soap:Body>" +

    //     "</soap:Envelope>";
        xmlHttpRequest.send(soapMessage);
        return xmlhttp.responseXML;
    }

    //*********************************************************
    function gGetEntityList()
     {

        /*
        Description:   Retrieving a List of Attributes for an Entity
        Calls:   gQueryMetadataService()
        Returns:   arrEntity - array with logical name of entities
        arrDisplay - array with display names
        Example:
        var list = gGetEntityList();
        var logicalname = list[0];
        var displayname = list[1];
        gConvertTextToPickList('cm_attribute',logicalname);
        */

        var request = "<Request xsi:type='RetrieveAllEntitiesRequest'>" +
            "<MetadataItems>EntitiesOnly</MetadataItems>" +     //MetadataItems – The items you wish to retrieve e.g. EntitiesOnly, IncludeAttributes, IncludePrivileges, IncludeRelationships and All.
            "<RetrieveAsIfPublished>false</RetrieveAsIfPublished>" +  //RetrieveAsIfPublished – specifies whether you want to get a list of just the published entity metadata or all of the entity metadata.
            "</Request>";

        var arrEntity = new Array();
        var arrDisplay = new Array();
        var j = 0;

        var result = gQueryMetadataService(request);
        var logicalNames = result.selectNodes("//CrmMetadata/LogicalName");
        var displayNames = result.selectNodes("//CrmMetadata/SchemaName");

        for (var i = 0; i < logicalNames.length; i++) {

            //only show customizable entities
            if (result.selectNodes("//CrmMetadata/IsCustomizable")[i].text == 'true') {
                arrEntity[j] = logicalNames[i].text;
                arrDisplay[j] = (displayNames[i]) ? displayNames[i].text : logicalNames[i].text;
                j++;
            }
        }
        return [arrEntity.sort(), arrDisplay.sort()];
    }

    //*********************************************************
    function gGetAttributeList(entityName)
    {

        /*
        Description:   Retrieving a List of Attributes for an Entity
        Calls:   gQueryMetadataService()
        Example:  gGetAttributeList("account");
        Returns:   arrResults - array with logical names
        arrDisplay - array with display names
        Example:
        var list = gGetAttributeList();
        var logicalname = list[0];
        var displayname = list[1];
        gConvertTextToPickList('cm_attribute',logicalname);

        */
        
        var request = "<Request xsi:type='RetrieveEntityRequest'>" +
            "<MetadataId>00000000-0000-0000-0000-000000000000</MetadataId>" +
            "<EntityItems>IncludeAttributes</EntityItems>" + //EntityItems – The items we wish to retrieve e.g. IncludeAttributes, EntityOnly, IncludePrivileges, IncludeRelationships and All.
            "<LogicalName>" + entityName + "</LogicalName>" + //LogicalName – Schema name of the entity we are retrieving.
            "<IsCustomizable>1</IsCustomizable>" + //LogicalName – Schema name of the entity we are retrieving.
            "<RetrieveAsIfPublished>true</RetrieveAsIfPublished>" + //RetrieveAsIfPublished – specifies whether you want to get a list of just the published entity metadata or all of the entity metadata.
            "</Request>";
        var arrResults = new Array();
        var arrDisplay = new Array();

        var result = gQueryMetadataService(request);
        var schemaNames = result.selectNodes("//EntityMetadata/Attributes/Attribute/SchemaName");
        var displayNames = result.selectNodes("//EntityMetadata/Attributes/Attribute/DisplayName/LocLabels/LocLabel/Label");
        //alert(result.selectNodes("//EntityMetadata/Attributes/Attribute/DisplayName")[0].xml);
        for (var i = 0; i < schemaNames.length; i++)
        {
            //document.writeln(schemaNames[i].text);
            arrResults[i] = schemaNames[i].text.toLowerCase();
            arrDisplay[i] = (displayNames[i]) ? displayNames[i].text : schemaNames[i].text.toLowerCase();
        }
        return [arrResults.sort(), arrDisplay.sort()];
    }

    //*********************************************************
    function gConvertTextToPickList(controlId, valuearray, textarray) {

        /*
        Description:   Funcion to convert a nvarchar (text) field into a picklist
        Calls:   AddPickListValues()
        Returns:   nothing
        Example:  var arrValues = ['1','2','3'];
        var arrText = ['One','Two','Three'];
        gConvertTextToPickList('<your_textfield>',arrValues, arrText);
        */

        //Referance the Text field
        
        var textControl = document.getElementById(controlId);
        if (!textControl) { return; }

        if (!textarray || (valuearray.length != textarray.length)) {
            textarray = valuearray;
        }

        //Create a new Picklist (SELECT) control
        var picklistControl = document.createElement("SELECT");

        //Copy the Text field properties to the picklist
        picklistControl.id = textControl.id;
        picklistControl.req = textControl.req;

        //Set Required Style,  add the picklist values
        picklistControl.className = "ms-crm-SelectBox "; //"selectBox " v3.0
        AddPickListValues(picklistControl, valuearray, textarray);

        //load the picklist selected value from the text field (saved) datavalue
        picklistControl.value = textControl.getValue();
        textControl.parentElement.appendChild(picklistControl);  //append the picklist to the document
        textControl.parentElement.removeChild(textControl);   //remove the text field , we don't need it anymore.

        //*********************************************************
        function AddPickListValues(picklistControl, valuearray, textarray)
         {

             for (var i = 0; i < valuearray.length; i++)
             {
                //Create a new Option
                var option = document.createElement("OPTION");
                option.value = option.innerText = valuearray[i];
                option.text = option.innerText = textarray[i];
                picklistControl.appendChild(option);       //Add the option to the picklist
            }
        }
    }

    function getServerUrl()
    {
        
        var OrgServicePath = "/XRMServices/2011/Organization.svc/web";
        var serverUrl = "";
        if (typeof GetGlobalContext == "function") {
            var context = GetGlobalContext();
            serverUrl = context.getServerUrl();
        }
        else {
            if (typeof Xrm.Page.context == "object") {
                serverUrl = Xrm.Page.context.getServerUrl();
            }
            else {
                throw new Error("Unable to access the server URL");
            }
        }
        if (serverUrl.match(/\/$/)) {
            serverUrl = serverUrl.substring(0, serverUrl.length - 1);
        }
        return serverUrl + OrgServicePath;
    }

    //now call the function
    initializePicklists();

    i added the above javascript on load of the custom entity. i am getting an error that the "object doesn't support this property or method".

    When i tried to debug using VS 2010 its saying" no dissembly found ".

    Any Suggestions ??


    Saturday, February 21, 2015 7:03 AM