Search This Blog

Wednesday, January 29, 2014

Adding MultiSelect CheckBox on MS CRM 2011 Form

Following steps to create multi select checkbox control on MS CRM 2011 form.

1. Create a picklist fields with required options and add it to your CRM form.
2. this picklist field will be converted to checkbox control at runtime.
3. you need to create one more text field in CRM and place it on the form in hidden mode , this field is required to store and read values selected in CheckBox Control.

Call the function below on load of the form

in the below example  "ap_typeofbuilding" is my Picklist control which will be converted to CheckBox Control for Multi select options , and "ap_btypetext" is my text field to read and store values selected in checkbox control.



gMultiSelectBTList = function () {

    // PL - the picklist attribute; PLV - used to save selected picklist values 

    var PL = document.getElementById("ap_typeofbuilding");
    var PLV = document.getElementById("ap_btypetext");

    var picklist = "ap_typeofbuilding";
    var textfield = "ap_btypetext";

    if (!PLV || textfield == '') { PLV = null; }
    if (PL != null) {

        PL.style.display = "none";

        //PLV1.style.display = "none"; 

        // Create a DIV container 

        var addDiv = document.createElement("<div style='overflow-y:auto; height:80px; border:1px #6699cc solid; background-color:#ffffff;' />");

        //  var addDiv1 = document.createElement("<div style='overflow-y:auto; height:80px; border:1px #6699cc solid; background-color:#EAF3FF;' />"); 

        PL.parentNode.appendChild(addDiv);

        // Initialise checkbox controls 

        for (var i = 1; i < PL.options.length; i++) {
            var pOption = PL.options[i];

            if (!IsChecked(pOption.text))

                var addInput = document.createElement("<input type='checkbox' name=" + pOption1.text + " value=" + pOption1.value + " style='border:none; width:25px; align:left;' onclick='picklistOnClick(" + picklist + "," + textfield + ")' />");

            else

                var addInput = document.createElement("<input type='checkbox' name=" + pOption1.text + " value=" + pOption1.value + " checked='checked' style='border:none; width:25px; align:left;' onclick='picklistOnClick(" + picklist + "," + textfield + ")' />");

            var addLabel = document.createElement("<label />");

            addLabel.innerText = pOption.text;

            var addBr = document.createElement("<br>"); //it's a 'br' flag 



            PL.nextSibling.appendChild(addInput);
            PL.nextSibling.appendChild(addLabel);
            PL.nextSibling.appendChild(addBr);

        }



        // Check if it is selected 

        function IsChecked(pText) {

            if (!PLV) return;

            if (PLV.value != "") {

                var PLVT = PLV.value.split("|");

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

                    if (PLVT[i] == pText)

                        return true;

                }

            }

            return false;

        }

        picklistOnClick = function (oPL, oPLV) {

            if (!oPLV) return;

            oPLV.value = "";

            var getInput = oPL.nextSibling.getElementsByTagName("input");

            for (var i = 0; i < getInput.length; i++) {
                if (getInput[i].checked) {

                    oPLV.value += getInput[i].nextSibling.innerText + "|";
                }

            }

            //MUST DO THIS TO TRIGGER A SAVE EVENT

            var btypetext = Xrm.Page.data.entity.attributes.get("ap_btypetext");
            btypetext.setValue(PLV.value);

        }

    }

}

This is another function which will help you to read selected values in text field and selected them in CheckBox Control ( this is for existing records )

function ReadBTPickList()
{
    var PL = crmForm.all.ap_typeofbuilding;
    var getInput = PL.nextSibling.getElementsByTagName("input");
    var allbtype = Xrm.Page.getAttribute("ap_btypetext").getValue();
    if (allbtype != null) {
        var btype = allbtype.split('|');

        for (var i = 0; i < btype.length - 1; i++) {
            for (var j = 0; j < getInput.length - 1; j++) {
                if (getInput[j].name == btype[i]) {
                    getInput[j].checked = true;
                }
            }
        }

    }
}







Update SubGrid Control at Runtime on Entity Form

Updating Subgrid control on the MS CRM Form.
below example demonstrate the Subgrid on custom entity which will filter Contact in contact sub grid , on search of specific firstname and lastname.

 


function UpdateSubGrid()
        {

            var subgridcontact = window.parent.document.getElementById("contact_subgrid");
            var subgridlead = window.parent.document.getElementById("lead_subgrid");

            var fname = window.parent.Xrm.Page.getAttribute("new_firstname").getValue();
            var lname = window.parent.Xrm.Page.getAttribute("new_lastname").getValue();
            var phonenumber = window.parent.Xrm.Page.getAttribute("new_phonenumber").getValue();

            //If this method is called from the form OnLoad, make sure that the grid is loaded before   proceeding

            if (subgridcontact == null || subgridcontact.readyState != "complete")
             {
                 setTimeout('UpdateSubGrid()', 1000);
                 return;
            }
            if (subgridlead == null || subgridlead.readyState != "complete")
            {
                setTimeout('UpdateSubGrid()', 1000);
                return;
            }

            //Update the fetchXML that will be used by the grid - Search in Contact.
     

            var fetchXml = "<fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0'>";
            fetchXml += "<entity name='contact'> <attribute name='firstname'/> <attribute name='lastname'/> <attribute name='mobilephone'/>";
            fetchXml += "<order descending='false' attribute='firstname'/>";
            fetchXml += "<filter type='and'>";
            if (fname != null)
            {
                fetchXml += "<condition attribute='firstname' value='" + fname + "%' operator='like'/>";
             
            }
            if (lname != null)
            {
                fetchXml += "<condition attribute='lastname' value='" + lname + "%' operator='like'/>";
            }
            if (phonenumber != null)
            {
                fetchXml += "<condition attribute='mobilephone' value='" + phonenumber + "%' operator='like'/>";
            }
            fetchXml += "</filter>";
            fetchXml += "</entity>";
            fetchXml += " </fetch>";

            subgridcontact.control.SetParameter("fetchXml", fetchXml);
            //Force the subgrid to refresh
            subgridcontact.control.refresh();
       }

Read Entity Attributes in MS CRM 2011

below is the way to read Entity Attributes and Display in GridView

// please connect to your CRM organization using appropriate URL

           IOrganizationService crmservice;
            CrmConnection crmconn = new CrmConnection();
            crmservice = crmconn.Connect2CRMNew(orguri);

            RetrieveEntityRequest retrieveEntityRequest = new RetrieveEntityRequest
            {
                EntityFilters = EntityFilters.All,
                LogicalName = entityname,
                RetrieveAsIfPublished = true
            };

            RetrieveEntityResponse retrieveEntityResponse = (RetrieveEntityResponse)crmservice.Execute(retrieveEntityRequest);
            EntityMetadata currentEntity = retrieveEntityResponse.EntityMetadata;
           
            // Attributes
           
            DataTable dtmain = new DataTable();
            dtmain.Columns.Add(new DataColumn("Schema name"));
            dtmain.Columns.Add(new DataColumn("Data Type"));
            dtmain.Columns.Add(new DataColumn("Size"));
            dtmain.Columns.Add(new DataColumn("Required Level"));
            dtmain.Columns.Add(new DataColumn("Is Audit Enabled"));
            dtmain.Columns.Add(new DataColumn("Is Custom Attribute"));
            dtmain.Columns.Add(new DataColumn("AttributeID"));
           
            foreach(AttributeMetadata allattributes in  currentEntity.Attributes)
            {
                DataRow dtrow = dtmain.NewRow();

                dtrow[0] = allattributes.LogicalName.ToString();
                dtrow[3] = allattributes.RequiredLevel.Value.ToString();
                dtrow[4] = allattributes.IsAuditEnabled.Value.ToString();
                dtrow[5] = allattributes.IsCustomAttribute.Value.ToString();
                dtrow[6] = allattributes.MetadataId.Value.ToString();
                dtrow[1] = allattributes.AttributeType.Value;

                switch (allattributes.AttributeType.Value.ToString())
                {
                    //case "Money":
                    //    dtrow[6] = ((Microsoft.Xrm.Sdk.Metadata.MoneyAttributeMetadata)(allattributes)).MaxValue.ToString();
                    //    break;
                    //case "Virtual":
                    //    dtrow[6] = ((Microsoft.Xrm.Sdk.Metadata.V)(allattributes)).MaxLength.ToString();
                    //    break;
                    case "Decimal":
                        dtrow[2] = ((Microsoft.Xrm.Sdk.Metadata.DecimalAttributeMetadata)(allattributes)).MaxValue.ToString();
                        break;
                    //case "Boolean":
                    //    //dtrow[6] = ((Microsoft.Xrm.Sdk.Metadata.BooleanAttributeMetadata)(allattributes)).
                    //    break;
                    //case "State":
                    //    //dtrow[6] = ((Microsoft.Xrm.Sdk.Metadata.StateAttributeMetadata)(allattributes)).
                    //    break;
                    case "String":
                        dtrow[2] = ((Microsoft.Xrm.Sdk.Metadata.StringAttributeMetadata)(allattributes)).MaxLength.ToString();
                        break;
                    //case "DateTime":
                    //    //dtrow[6] = ((Microsoft.Xrm.Sdk.Metadata.DateTimeAttributeMetadata)(allattributes)).
                    //    break;
                    case "Integer":
                        dtrow[2] = ((Microsoft.Xrm.Sdk.Metadata.IntegerAttributeMetadata)(allattributes)).MaxValue.ToString();
                        break;
                    //case "Lookup":
                    //    //dtrow[6] = ((Microsoft.Xrm.Sdk.Metadata.LookupAttributeMetadata)(allattributes)).
                    //    break;
                    //case "Uniqueidentifier":
                    //    //dtrow[6] = ((Microsoft.Xrm.Sdk.Metadata.Uniq)(allattributes)).
                    //    break;
                    //case "Picklist":
                    //    //dtrow[6] = ((Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata)(allattributes)).OptionSet.
                    //    break;



                };
                dtmain.Rows.Add(dtrow);
            }
            gvAttributes.DataSource = dtmain.DefaultView;
            gvAttributes.DataBind();
            pnlattribute.Visible = true;
            Session.Add("TaskTable",dtmain);

Merge Records in MS CRM 2011 using C#

following in the code to Merge 2 records through Asp.Net

 // Connect to CRM 2011
                    IOrganizationService crmservice;
                    CrmConnection conn = new CrmConnection();
                    crmservice = conn.Connect2CRM();

// below are 2 sample account records





                    //D9E2197D-244C-E211-9675-005056B0000B // Test Account - Vilas M
                    //BA59DFF0-E939-E211-946D-005056B0000B // Test Company - Vilas

                    MergeRequest mreq = new MergeRequest();
                    Guid targetAccountID =  new Guid("D9E2197D-244C-E211-9675-005056B0000B");
                    Guid tobemergedAccountID =  new Guid("BA59DFF0-E939-E211-946D-005056B0000B");
                    mreq.Target = new EntityReference("account", targetAccountID);  // Target Account ID , where other account will be mergered
                    mreq.SubordinateId = tobemergedAccountID;

                    Entity entAccnt = new Entity("account");
                    entAccnt.Attributes["Address1_Line1"] = "Test";

                    mreq.UpdateContent = entAccnt;

                    MergeResponse mresp = (MergeResponse)crmservice.Execute(mreq);
                    Console.WriteLine("Sucessfully Merged !! ");