Wednesday 26 November 2014

Meta Data in DropDown List in CRM 2013

Hi,

this page explains how we can bring and show the metadata in dropdown list(in HTML page).

1. Download the latest SDK.

go to : SDK\SampleCode\JS\SOAPForJScript\SOAPForJScript\Scripts

   check SDK.MetaData.js is there or not..
if yes :

2. Create a javascript webresource with name of : SDK.MetaData
   example : new_/Scripts/SDK.MetaData.js (use same formate for naming)

3. attach the SDK.MetaData.js from bin folder.

4. now create a HTML webresource with name of : /MetaDataDemo.htm

example : new_/MetaDataDemo.htm (use same format for naming).

5. attach the file : SDK\SampleCode\JS\SOAPForJScript\SOAPForJScript\MetaDataDemo.htm

here you will see the start button.. by clicking on this we will get entities, by clicking on entity we will get attributes.

now need to modify according to our requirement.

copy paste this code on the html webresource;

<!DOCTYPE html>
<!--
This file is part of the Microsoft Dynamics CRM SDK code samples.

Copyright (C) Microsoft Corporation.  All rights reserved.

This source code is intended only as a supplement to Microsoft
Development Tools and/or on-line documentation.  See these other
materials for detailed information regarding Microsoft code samples.

THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
-->
<!--<snippetMetaDataDemo>-->
<html lang="en-US">
<head>
    <title>Metadata Demonstration</title>
    <script src="../ClientGlobalContext.js.aspx" type="text/javascript"></script>
    <script src="hppscm_/Scripts/SDK.MetaData.js" type="text/javascript"></script>
    <script type="text/javascript">
        // An unordered list element to add Entity list items to
        var results;
        // An area to display messages
        var message;

        // Alert flag to indicate the changes
        // var alertFlag;

        function startSample() {
            ///<summary>
            /// Initializes the sample when the document is ready
            ///</summary>
            //Assign the global variables
            results = document.getElementById("results");
            message = document.getElementById("message");
            //    alertFlag = document.getElementById("dispalert");
            // document.getElementById("btnstartSample").setAttribute("disabled", "disabled");
            //Retrieve entities
            window.parent.SDK.Metadata.RetrieveAllEntities(window.parent.SDK.Metadata.EntityFilters.Entity,
             false,
             successRetrieveAllEntities,
             errorRetrieveAllEntities);
            // setText(message, "Loading...");

        }
        function btnSubmitValues() {
            var placeHValue = document.getElementById("placeholder");
            var dropdValue = document.getElementById("attributeselect");
            var EntityList= document.getElementById("entityselect");
            var seletedvalue = dropdValue.options[dropdValue.selectedIndex].text;
            var entityselectevalue = EntityList.options[EntityList.selectedIndex].text;
          //  var merge = placeHValue.value + seletedvalue;

            var Xrm;
            if (window.opener) { Xrm = window.opener.Xrm; }
            else if (window.parent) { Xrm = window.parent.Xrm; }
            var Formname = Xrm.Page.getAttribute("hppscm_name").getValue();
            var FormField = Xrm.Page.getAttribute("hppscm_field").getValue();

            Xrm.Page.getAttribute("hppscm_name").setValue(placeHValue.value);
            Xrm.Page.getAttribute("hppscm_field").setValue(seletedvalue);
            Xrm.Page.getAttribute("hppscm_entity").setValue(entityselectevalue);
           // alert(merge);

        }

        function successRetrieveAllEntities(entityMetadataCollection) {
            ///<summary>
            /// Receives the data from SDK.Metadata.RetrieveAllEntities and
            /// appends a list item to results for each one.
            ///</summary>

            entityMetadataCollection.sort(function (a, b) {
                if (a.LogicalName < b.LogicalName)
                { return -1 }
                if (a.LogicalName > b.LogicalName)
                { return 1 }
                return 0;
            });

            var EntityDropdown = document.getElementById('entityselect');
            var totalfields = entityMetadataCollection.length;
            var optionsList = new Array(totalfields);

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

                var entity = entityMetadataCollection[i];
                var entityNode = document.createElement("li");
                var entitySpan = document.createElement("span");

                setText(entitySpan, entity.SchemaName);
                entitySpan.id = entity.LogicalName;
                optionsList[i] = entity.LogicalName;
                entitySpan.title = "Click to Retrieve Attributes.";
                entitySpan.attributesRetrieved = false;
                // Add the event handler to retrieve attributes
                if (entity.LogicalName == "hppscm_visaapplication") {
                    entitySpan.onload = retrieveAttributes;
                   // EntityDropdown.options[i].selected=true;
                    entitySpan.onclick = retrieveAttributes;
                    entitySpan.style.cursor = "pointer";

                   // entityNode.appendChild(entitySpan);
                   // results.appendChild(entityNode);
                }
            }

            for (var i = 0; i < optionsList.length; i++) {
                option = new Option(optionsList[i], optionsList[i]);
                EntityDropdown.appendChild(option);// = option;
                if(optionsList[i]=="hppscm_visaapplication")
                {
                    EntityDropdown.options[i].selected = true;
                }
            }

            //setText(message, entityMetadataCollection.length +
            //" entities retrieved. Click each entity to retrieve the entity attributes.");

            retrieveAttributes();
        }
        function errorRetrieveAllEntities(error) {
            ///<summary>
            /// Displays the error returned from  SDK.Metadata.RetrieveAllEntities if it fails.
            ///</summary>
            setText(message, error.message);

        }

        function retrieveAttributes() {
            ///<summary>
            /// Retrieves attributes for the entity list item that is clicked
            ///</summary>
            //  if (this.attributesRetrieved == false) {
            var EntityList = document.getElementById("entityselect");
            //var seletedvalue = dropdValue.options[dropdValue.selectedIndex].text;
            var entityselectevalue = EntityList.options[EntityList.selectedIndex].text;
            var entityLogicalName = entityselectevalue;//this.id;
                // Display an entity list item level notification while retrieving data.
                var notification = document.createElement("span");


                setText(notification, "   Retrieving attributes for " + entityLogicalName + "...");
                notification.id = entityLogicalName + "Notification";
              //  entityLogicalName.parentElement.appendChild(notification);

                window.parent.SDK.Metadata.RetrieveEntity(window.parent.SDK.Metadata.EntityFilters.Attributes,
                entityLogicalName,
                null,
                false,
                function (entityMetadata) { successRetrieveEntity(entityLogicalName, entityMetadata); },
                errorRetrieveEntity);


           // }
            //this.attributesRetrieved = true;
          //  this.title = "";
        }

        function successRetrieveEntity(logicalName, entityMetadata) {
            ///<summary>
            /// Retrieves attributes for the entity list item that is clicked
            ///</summary>

            // Update the entity list item notification when data is retrieved.

            entityMetadata.Attributes.sort(function (a, b) {
                if (a.LogicalName < b.LogicalName)
                { return -1 }
                if (a.LogicalName > b.LogicalName)
                { return 1 }
                return 0;
            });

            //var notification = setText(document.getElementById(logicalName +
            //"Notification"), "   Retrieved " + entityMetadata.Attributes.length + " attributes.");

            var attributeList = document.createElement("ul");
            var dropdownlist = document.getElementById('attributeselect');
            var totalfields = entityMetadata.Attributes.length;
            var optionsList = new Array(totalfields);

            for (var i = 0; i < entityMetadata.Attributes.length; i++) {
                var attribute = entityMetadata.Attributes[i];
                var attributeNode = document.createElement("li");
                setText(attributeNode, attribute.SchemaName);
                attributeList.appendChild(attributeNode);
                optionsList[i] = attribute.SchemaName;

            }

            for (var i = 0; i < optionsList.length; i++) {
                option = new Option(optionsList[i], optionsList[i]);
                dropdownlist.appendChild(option);// = option;
            }

            //for (i = 0; i < attributeList.childNodes.length; i++)
            //{
            //    var opt = document.createElement("option");
            //    opt.text = attributeList.childNodes[i].innerText;
            //    opt.value = i;
            //    dropdownlist.appendChild(opt);

            //}
            // Access the entity list item element
      //      var entityNode = document.getElementById(logicalName).parentElement;

            // entityNode.appendChild(attributeList);
            // entityNode.attributesDisplayed = true;
            // Attach event handler to toggle display of attributes.
         //   entityNode.firstChild.onclick = toggleDisplayAttributes;
         //   entityNode.firstChild.title = "Click to hide attributes.";

        }
        function errorRetrieveEntity(error) {
            ///<summary>
            /// Displays the error returned from SDK.Metadata.RetrieveEntity if it fails.
            ///</summary>
            setText(message, error.message);

        }

        function toggleDisplayAttributes() {
            ///<summary>
            /// toggles whether the list of attributes is displayed.
            ///</summary>

            if (this.parentElement.attributesDisplayed) {
                this.parentElement.lastChild.style.display = "none";
                this.parentElement.attributesDisplayed = false;
                this.title = "Click to show attributes.";


            }
            else {
                this.parentElement.lastChild.style.display = "block";
                this.parentElement.attributesDisplayed = true;
                this.title = "Click to hide attributes.";


            }

        }

        // setText and getText mitigate differences in how browsers set or get text content.
        function setText(node, text) {
            if (typeof (node.innerText) != "undefined") {
                node.innerText = text;
            }
            else {
                node.textContent = text;
            }

        }

        function getText(node) {
            if (typeof (node.innerText) != "undefined") {
                return node.innerText;
            }
            else {
                return node.textContent;
            }
        }

    </script>
</head>
<body style="font-family: Segoe UI;" onload="startSample()">
    <!--<h1>
        Metadata Demonstration Sample
    </h1>
    <p>
        This form requires JavaScript and will update the page dynamically.
    </p>-->
    <p>
        <!--<input id="dispalert" name="dispalert" type="checkbox" value="alert" /><label for="dispalert">Display alert window when data changes.</label> <br>-->
        Place Holder: <input type="text" name="PlaceHolder" id="placeholder"> <br />
        Entity : <select id="entityselect" name="Entities" onchange ="retrieveAttributes()"></select>
        Field : <select id="attributeselect" name="Attributes"></select>
    </p>
    <p>
        <label id="lblstartSample" for="btnstartSample">
        </label>
        <input type="button" id="btnstartSample" name="btnstartSample" value="Submit" onclick="btnSubmitValues()" />
        <!--<input type="button" id="btnstartSample" name="btnstartSample" value="Submit" onclick="startSample()" />-->
    </p>
    <div id="message">
    </div>
    <ul id="results"></ul>
</body>
</html>
<!--</snippetMetaDataDemo>-->


then you will see the page: