Monday, January 31, 2022

Dynamics 365: CRUD Operations-3 (Create Item)

Hello Friends,

Welcome back with another post on Dynamics 365. This post is the 3rd part of CRUD operations.

In last post, we have fetched all records from Account Entity.

Dynamics 365: CRUD Operations-1 (Basic Preparations)

Dynamics 365: CRUD Operations-2 (Retrieve All Items)

Now, we will learn about how to create item in D365 >> Account entity.

  1. Here we will create an HTML to input below fields-
    1. Account Name
    2. Primary Contact Person ( we will take the ID of the contact entity. we are displaying this value in grid itself)
    3. Account Category Code (Preferred - 1 / Standard - 2)
    4. Annual Revenue
    5. Main Phone
  2. Below is the complete HTML. This HTML includes code of previous post as well. You may copy/paste this entire HTML.
  3. <html>
        <head></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">
            <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">
            <link href="https://unpkg.com/bootstrap-table@1.18.1/dist/bootstrap-table.min.css" rel="stylesheet">
            
            <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>
            <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://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>
            <script src="https://unpkg.com/tableexport.jquery.plugin/tableExport.min.js"></script>
            <style type="text/css">
                .footer {
                    position: fixed;
                    bottom: 0;
                    right: 0;
                    padding-bottom: 10px;
                    padding-right: 10px;
                }
        
                .footerButton {
                    width: 150px;
                }
            </style>
            <div>
                <table id="tblCreateRecord" style="width: 100%;">
                    <tr>
                        <td style="width: 50%;">Account Name</td>
                        <td style="width: 5%;">:</td>
                        <td style="width: 45%;"><input type="text" id="txtAccountName"></td>
                    </tr>
                    <tr>
                        <td style="width: 50%;">Primary Contact Person (ID)</td>
                        <td style="width: 5%;">:</td>
                        <td style="width: 45%;"><input type="text" id="txtPrimaryContactPersonID"></td>
                    </tr>
                    <tr>
                        <td style="width: 50%;">Account Category Code (Preferred Customer-1 / Standard-2)</td>
                        <td style="width: 5%;">:</td>
                        <td style="width: 45%;"><input type="text" id="txtAccountCategoryCode"></td>
                    </tr>
                    <tr>
                        <td style="width: 50%;">Annual Revenue</td>
                        <td style="width: 5%;">:</td>
                        <td style="width: 45%;"><input type="text" id="txtAnnualRevenue"></td>
                    </tr>
                    <tr>
                        <td style="width: 50%;">Primary Phone</td>
                        <td style="width: 5%;">:</td>
                        <td style="width: 45%;"><input type="text" id="txtPrimaryPhone"></td>
                    </tr>
                    <tr>
                        <td colspan="3"><input type="button" onclick="fnCreateRecord();return false;" value="Create Record"/></td>
                    </tr>
                    
                </table>
            </div>
            <div>
                <table id="table" data-search="true" data-header-style="headerStyle" data-page-size="25">
                    <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="mainphone" data-sortable="true">Main Phone</th>
                            <th data-field="primaryemail" data-sortable="true">EMail (Primary)</th>
                            <th data-field="primarycontact" data-sortable="true">Primary Contact</th>
                            <th data-field="primarycontactname" data-sortable="true">Primary Contact Name</th>
                            <th data-field="updateitem" data-sortable="false">Update</th>
                        </tr>
                    </thead>
                </table>
            </div>
        </body>
        <script type="text/javascript">
            $(document).ready(function(){
                fnGetAllAccounts();
            });
            function fnGetAllAccounts() 
            {
                //var query = '?$select=accountcategorycode,address1_addressid,address1_longitude,donotphone,name,_primarycontactid_value,revenue';
                var query = '?$select=accountid,name,telephone1,emailaddress1,_primarycontactid_value';
                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 accountid = result["accountid"];
                        var name = result["name"];
                        var telephone = result["telephone1"];
                        var emailaddress = result["emailaddress1"];
                        var primarycontactid = result["_primarycontactid_value"];
                        var primarycontactname = result["_primarycontactid_value@OData.Community.Display.V1.FormattedValue"];
                        
                        var accountRecord = {};  
                        accountRecord =  
                        {  
                            'id': accountid,
                            'name': name,
                            'account': accountid,
                            'mainphone': telephone,
                            'primaryemail':emailaddress,
                            'primarycontact':primarycontactid,
                            'primarycontactname':primarycontactname,
                            'updateitem':'<a href="javascript:void(0);" onclick="fnUpdateAccount(\'' + accountid + '\');return false;">Update</a>'
                        }  
                        accountRecords.push(accountRecord);  
                    });
                    $('#table').bootstrapTable({ data: accountRecords });  
                },
                function (error) {
                    console.log(error.message);
                    reject(Error(error.message));
                });
            }
    
            function fnCreateRecord()
            {
                var entityData =
                {
                    "name": $('#txtAccountName').val(),
                    "primarycontactid@odata.bind": "/contacts(" + $('#txtPrimaryContactPersonID').val() + ")", //--- Lookup --- Display Text = Primary Contact
                    "accountcategorycode": $('#txtAccountCategoryCode').val(),     // Option Set --- Display Text = Category
                    "revenue": parseFloat($('#txtAnnualRevenue').val()),        // Currency (money type) ---Display Text = Annual Revenue
                    "telephone1":$('#txtPrimaryPhone').val()
                }
                window.parent.Xrm.WebApi.createRecord("account", entityData).then(
                    function success(result) {
                        //Success - No Return Data
                        alert("Account created successfully.");
                    },
                    function (error) {
                        alert(error.message);
                    }
                );
            }
        </script>
    </html>
    
  4. You need to copy/paste this HTML in Web Resource file we discussed in previous post.
  5. Save the Web Resource file and then publish it. Now refresh the D365 page (Ctrl + F5).
  6. It will appear as below-
  7. Input some values.
  8. Here, for contact Id, we have picked the Id of Haroun Stormonth from the given table, we have loaded.
  9. Now click on "Create Record" button. It will prompt a message-
  10. Now, go to Account entity or just refresh the page.

  11. This way, a new account gets created.
  12. The API used is:-
    1. window.parent.Xrm.WebApi.createRecord
  13. In Next post, we will try to update the read the individual record from Account Entity.
  14. Next Post-
    1. Dynamics 365: CRUD Operations-4 (Read Item)
With this, I am concluding this post.
Happy Coding !!!
Will see you again with some new topics.

Stay Safe !
Stay Healthy !

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.