Search This Blog

Sunday, January 30, 2022

CRUD Opertations with Xrm.WebApi.online

<html><head>  

    <title>Modal Dialog</title>  

<meta><meta><meta><meta><meta></head>  

<body onfocusout="parent.setEmailRange();" style="overflow-wrap: break-word;">  

    <meta charset="utf-8">  

    <link rel="stylesheet" href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/css/fabric.min.css">  

    <link rel="stylesheet" href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/css/fabric.components.min.css">  

    <!-- <script type="text/javascript" src="../ClientGlobalContext.js.aspx"></script>   -->


    <script src="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/js/fabric.min.js"></script>  

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">  

  

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>  

    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>  

    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>  

  

    <style type="text/css">  

        .footer {  

            position: fixed;  

            bottom: 0;  

            right: 0;  

            padding-bottom: 10px;  

            padding-right: 10px;  

        }  

  

        .footerButton {  

            width: 150px;  

        }  

    </style>  

    <script type="text/javascript">

        var Category = {

            PreferredCustomer : 1,

            Standard: 2

        };

        var accountId = '';//'6869103d-d281-ec11-8d21-000d3ac9f173';

        $(document).ready(function () {  

            //retrieveMultiple();

            //createRecord();

            //updateRecord();

            //deleteRecord();

            retrieveMultiple();

            

        });  

  

        function getUrlParameters() {  

            var queryString = location.search.substring(1);  

            return queryString;  

        } 



        function createRecord() 

        {


            var accountInfo = '';

            var accountName = "Alex Ferguson";

            var primaryContactId = "9fd4a450-cb0c-ea11-a813-000d3a1b1223"; //-- Amrit Consultancies

            var primaryContactName = "Dwayne Elijah";

            var accountCategoryCode = Category.Standard;

            var annualRevenue = 7500000;


            var entityData =

            {

                "name": accountName,

                "revenue": annualRevenue,        // Currency (money type) ---Display Text = Annual Revenue

                "donotphone": false,    //Two Option (boolean type) ---Display Text = Do not allow Phone Calls

                "address1_longitude": 112.512634,     //Floating Point Number (decimal type) --- Display Text = Address 1: Longitude

                "address1_composite": "This is address 1",  //Multiple Lines of Text (memo type) --- Display Text = Address 1

                "accountcategorycode": accountCategoryCode,     // Option Set --- Display Text = Category

                "primarycontactid@odata.bind": "/contacts(" + primaryContactId + ")" //--- Lookup --- Display Text = Primary Contact

            }


            window.parent.Xrm.WebApi.createRecord("account", entityData).then(

                function success(result) {

                    //Success - No Return Data

                    accountId = result.id;

                    var accountInfo = '';

                    accountInfo += 'Account Name = ' + accountName + '\n';

                    accountInfo += 'Primary Contact = ' + primaryContactName + '\n';

                    accountInfo += 'Category = Standard \n';

                    accountInfo += 'Annual Revenue = ' + annualRevenue + '\n';


                    alert("Account created. Details are given below : \n\n" + accountInfo + "\n\n" + "Going to update this record now.");

                    //updateRecord();

                    //return accountId;

                },

                function (error) {

                    alert(error.message);

                }

            );

        }






        function updateRecord() {

            if (accountId != '') {

                var accountInfo = '';


                var accountName = "Modified - Alex Ferguson";

                var primaryContactId = "cdd6a450-cb0c-ea11-a813-000d3a1b1223"; //-- Adrian Dumitrascu

                var primaryContactName = "Haroun Stormonth";

                var accountCategoryCode = Category.PreferredCustomer;

                var annualRevenue = 800000;

                var telephone1 = "8587016875";


                var entityData =

                {

                    "name": accountName,

                    "revenue": annualRevenue,        // Currency (money type) ---Display Text = Annual Revenue

                    "donotphone": true,    //Two Option (boolean type) ---Display Text = Do not allow Phone Calls

                    "address1_longitude": 78.23625,     //Floating Point Number (decimal type) --- Display Text = Address 1: Longitude

                    "address1_composite": "Modified - This is address 1",  //Multiple Lines of Text (memo type) --- Display Text = Address 1

                    "accountcategorycode": accountCategoryCode,     // Option Set --- Display Text = Category

                    "telephone1": telephone1,

                    //--Contact Name = Adrian Dumitrascu

                    "primarycontactid@odata.bind": "/contacts(" + primaryContactId + ")" //--- Lookup --- Display Text = Primary Contact

                }


                window.parent.Xrm.WebApi.updateRecord("account", accountId, entityData).then(

                                function success(result) {


                                    var accountInfo = '';

                                    accountInfo += 'Account Name = ' + accountName + '\n';

                                    accountInfo += 'Primary Contact = ' + primaryContactName + '\n';

                                    accountInfo += 'Category = Preferred Customer \n';

                                    accountInfo += 'Annual Revenue = ' + annualRevenue + '\n';


                                    alert("Account updated successfully. Details are given below : \n\n" + accountInfo + "\n\n" + "Going to retrieve record.");


                                    

                                },

                                function (error) {

                                    debugger;

                                    // handle error conditions

                                    console.log(error.message);

                                    reject(error.message);

                                }

                            );

            }

        }





        function deleteRecord() {

            if (accountId != '') {

                window.parent.Xrm.WebApi.deleteRecord("account", accountId).then(

                function success(result) {

                    alert("Account deleted successfully. \n\n" + "Going to call retrieveMultiple() function now.");

                    // perform operations on record deletion

                    //retrieveMultiple();

                },

                function (error) {

                    debugger;

                    console.log(error.message);

                    // handle error conditions

                }); 

            }

        }





        function retrieveMultiple() 

        {

            var query = '?$select=accountcategorycode,address1_addressid,address1_longitude,donotphone,name,_primarycontactid_value,revenue';

            window.parent.Xrm.WebApi.online.retrieveMultipleRecords("account", query).then(

            function success(accounts) 

            {

                var results = accounts.entities;

                    var accountRecords = [];  

                results.forEach(function (result, index, array) 

                {

                    var _primarycontactid_value = result["_primarycontactid_value"];

                    var _primarycontactid_navigation_property = result["_primarycontactid_value@Microsoft.Dynamics.CRM.associatednavigationproperty"];

                    var _primarycontactid_value_lookuplogicalname = result["_primarycontactid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];

                    var _primarycontactid_value_formatted = result["_primarycontactid_value@OData.Community.Display.V1.FormattedValue"];


                    var _transactioncurrencyid_value = result["_transactioncurrencyid_value"];

                    var _transactioncurrencyid_navigation_property = result["_transactioncurrencyid_value@Microsoft.Dynamics.CRM.associatednavigationproperty"];

                    var _transactioncurrencyid_value_lookuplogicalname = result["_transactioncurrencyid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];

                    var _transactioncurrencyid_value_formatted = result["_transactioncurrencyid_value@OData.Community.Display.V1.FormattedValue"];


                    var accountcategorycode = result["accountcategorycode"];

                    var accountcategorycode_formatted = result["accountcategorycode@OData.Community.Display.V1.FormattedValue"];


                    var accountid = result["accountid"];

                    var address1_addressid = result["address1_addressid"];


                    var address1_longitude = result["address1_longitude"];

                    var address1_longitude_formatted = result["address1_longitude@OData.Community.Display.V1.FormattedValue"];


                    var donotphone = result["donotphone"];

                    var donotphone_formatted = result["donotphone@OData.Community.Display.V1.FormattedValue"];


                    var name = result["name"];


                    var revenue = result["revenue"];

                    var revenue_formatted = result["revenue@OData.Community.Display.V1.FormattedValue"];


                    var accountRecord = {};  

                    accountRecord =  

                    {  

                    'name': name,  

                    'account': accountid,  

                    'revenue': revenue,  

                    'id': accountid,

                    'editcode':'<a href="javascript:void(0);" onclick="(function(){accountId=\''+_primarycontactid_value+'\'; openEditForm();})();return false;">Edit</a>'

                    }  

                    accountRecords.push(accountRecord);  

                });

                $('table').bootstrapTable({ data: accountRecords });  


                //alert("Executed function retrieveMultipleRecords() successfully. \n\n "+ "Total Accounts retrieved = " + results.length);

            },

            function (error) {

                debugger;

                console.log(error.message);

                // Reject promise

                reject(Error(error.message));

            });

        }


        function openEditForm()

        { // REDIRECT TO FORM

            var entityFormOptions = {};

            //Entity Name of which form is to open

            entityFormOptions["entityName"] = "contact";

            

            //Below parameter is required if you want ot edit a particular record

            //entityFormOptions["entityId"] = accountId;


            //Below parameter is required if you wish to open Quick Edit Form

            entityFormOptions["useQuickCreateForm"] = true;



            // Open the form.

            window.parent.Xrm.Navigation.openForm(entityFormOptions).then(

                function (success) {

                    console.log(success);

                },

                function (error) {

                    console.log(error);

            });

            

        }



        /* 

        function loadRecords(recordId) {  

  

            var $table = $("#leadtable");  

  

            var req = new XMLHttpRequest();  

            req.open("GET", parent.Xrm.Page.context.getClientUrl() + "/api/data/v9.1/leads?$select=_accountid_value,createdon,description,fullname", false);  

            req.setRequestHeader("OData-MaxVersion", "4.0");  

            req.setRequestHeader("OData-Version", "4.0");  

            req.setRequestHeader("Accept", "application/json");  

            req.setRequestHeader("Content-Type", "application/json; charset=utf-8");  

            req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");  

            req.onreadystatechange = function () {  

                if (this.readyState === 4) {  

                    req.onreadystatechange = null;  

                    if (this.status === 200) {  

                        var results = JSON.parse(this.response);  

  

                        var leadRecords = [];  

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

                            var _accountid_value = results.value[i]["_accountid_value"];  

                            var _accountid_value_formatted = results.value[i]["_accountid_value@OData.Community.Display.V1.FormattedValue"];  

                            var _accountid_value_lookuplogicalname = results.value[i]["_accountid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];  

                            var createdon = results.value[i]["createdon"];  

                            var description = results.value[i]["description"];  

                            var fullname = results.value[i]["fullname"];  

                            var leadid = results.value[i]["leadid"];  

  

                            var leadRecord = {};  

                            leadRecord =  

                            {  

                                'name': fullname,  

                                'account': _accountid_value,  

                                'description': description,  

                                'id': leadid  

  

                            }  

                            leadRecords.push(leadRecord);  

                        }  

                        $('table').bootstrapTable({ data: leadRecords });  

  

                    }  

                    else {  

                        Xrm.Utility.alertDialog(this.statusText);  

                    }  

                }  

            };  

            req.send();  

  

        }  

        */

    </script>     

    <div>  

        <table id="table" data-search="true" data-header-style="headerStyle" data-page-size="2">  

            <thead>  

                <tr>  

                    <th data-field="id" data-visible="false" data-checkbox="true">Id</th>  

                    <th data-field="name" data-sortable="true">Full Name</th>  

                    <th data-field="account" data-sortable="true">Account</th>  

                    <th data-field="revenue" data-sortable="true">Description</th>

                    <th data-field="editcode" data-sortable="false">Edit</th>

                </tr>  

            </thead>  

        </table>  

    </div>  

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>  

    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>  

    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>  

    <script src="https://unpkg.com/bootstrap-table@1.16.0/dist/bootstrap-table.min.js"></script>  

    <link href="https://unpkg.com/bootstrap-table@1.18.1/dist/bootstrap-table.min.css" rel="stylesheet">  

    <script src="https://unpkg.com/tableexport.jquery.plugin/tableExport.min.js"></script>  

  

</body></html>


No comments:

Post a Comment