Bhubaneswar, Odisha, India
+91-8328865778
support@softchief.com

CRUD Operation from Power Portal using WEB API Methods

CRUD Operation from Power Portal using WEB API Methods

We can perform crud operation from power portals using web API check the below code and watch the video to understand more,

FULL CODE HERE

<div class="container" style="margin:100px">
{% fetchxml contactList %}
    <fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
    <entity name="contact">
    <attribute name="fullname" />
    <attribute name="telephone1" />
    <attribute name="emailaddress1" />
    <attribute name="contactid" />
     <attribute name="firstname" />
    <order attribute="fullname" descending="false" />
    <filter type="and">
      <condition attribute="firstname" operator="eq" value="Andrew" />
      <condition attribute="statecode" operator="eq" value="0" />
    </filter>
  </entity>
</fetch>
{% endfetchxml %}

<button id="updateContact" class="btn btn-success btn-large" onclick="update();">Submit</button>
<button id="deleteContact" value="Delete" class="btn btn-danger btn-large " style:"margin-left:20px>Delete</button>
<table id="tblData" class="table" style="border:1px solid">
        <thead class="thead-dark">
            <tr class="table-heading">
               <th><input type="checkbox" id="checkedAll" style="margin-left:30px"/></th>
                <th>First Name</th>
                <th>Email</th>
                <th>Business Phone</th>
            </tr>
        </thead>
        <tbody>
        {% for result in contactList.results.entities %}
       {% assign contactids  = result.contactid %}
        <tr>
            <td><input type="checkbox" id="{{ result.contactid }}" class="contactIDs" style="margin-left:30px" onchange="pushArrayCheckBox(this);" /></td>
            <td><input type="text" id="txtfullName|{{result.contactid}}" contactid="{{result.contactid}}" value="{{ result.firstname }}" onchange="pushArray(this);"></td>
            <td>{{ result["emailaddress1"] }}</td>
            <td><input type="number" id="txtBusinessPhone|{{result.contactid}}" contactid="{{result.contactid}}" value="{{ result.telephone1 }}" pattern="\d*" title="Please enter Numbers only..." onchange="pushArray(this);"></td>
          
         </tr>
          <tr class="no-records" style="display: none;">
             <td colspan='6'>No Record Found</td>
         </tr>
        {% endfor %}
         
    </tbody>
</table>
</div>
(function(webapi, $) {
    function safeAjax(ajaxOptions) {
        var deferredAjax = $.Deferred();
        shell.getTokenDeferred().done(function(token) {
            // add headers for AJAX                 
            if (!ajaxOptions.headers) {
                $.extend(ajaxOptions, {
                    headers: {
                        "__RequestVerificationToken": token
                    }
                });
            } else {
                ajaxOptions.headers["__RequestVerificationToken"] = token;
            }
            $.ajax(ajaxOptions).done(function(data, textStatus, jqXHR) {
                validateLoginSession(data, textStatus, jqXHR, deferredAjax.resolve);
            }).fail(deferredAjax.reject);
            //AJAX             
        }).fail(function() {
            deferredAjax.rejectWith(this, arguments);
            // on token failure pass the token AJAX and args           
        });
        return deferredAjax.promise();
    }
    webapi.safeAjax = safeAjax;
})(window.webapi = window.webapi || {}, jQuery)

//custom code 
var globalArray = [];

function pushArray(currentObject) {
    var str = currentObject.id;
    var res = str.split("|");
    var contId = res[1];
    var checkbox = document.getElementById(contId).checked;
    var fullname = document.getElementById("txtfullName|" + contId).value;
    var phonenumber = document.getElementById("txtBusinessPhone|" + contId).value;
    let objIndex = globalArray.findIndex((obj => obj.id == contId));
    if (objIndex == -1) {
        globalArray.push({
            id: contId,
            fullname: fullname,
            phone: phonenumber,
            checkboxval: checkbox
        })
    } else {
        globalArray[objIndex].fullname = fullname;
        globalArray[objIndex].phone = phonenumber;
        globalArray[objIndex].checkboxval = checkbox;
    }
}

function pushArrayCheckBox(currentObject) {
    var contId = currentObject.id;
    var checkbox = document.getElementById(contId).checked;
    var fullname = document.getElementById("txtfullName|" + contId).value;
    var phonenumber = document.getElementById("txtBusinessPhone|" + contId).value;
    let objIndex = globalArray.findIndex((obj => obj.id == contId));
    if (objIndex == -1) {
        globalArray.push({
            id: contId,
            fullname: fullname,
            phone: phonenumber,
            checkboxval: checkbox
        })
    } else {
        globalArray[objIndex].fullname = fullname;
        globalArray[objIndex].phone = phonenumber;
        globalArray[objIndex].checkboxval = checkbox;
    }
}

function update(flag) {
    var i;
    for (i = 0; i < globalArray.length; i++) { //update checked row changes 
        alert(globalArray[i].fullname + "-" + globalArray[i].phone + "-" + globalArray[i].checkboxval);
        if (globalArray[i].checkboxval == 1) //true
        {
            document.getElementById("processingMsg").innerHTML = "Processing....";
            try {
                let value = {
                    "firstname": globalArray[i].fullname,
                    "telephone1": globalArray[i].phone
                };
                if (flag == "U") {
                    webapi.safeAjax({
                        type: "PATCH",
                        url: "/_api/contacts(" + globalArray[i].id + ")",
                        contentType: "application/json",
                        data: JSON.stringify(value),
                        success: function(res) {
                            document.getElementById("processingMsg").innerHTML = "Records updated successfully.";
                        }
                    });
                } else if (flag == "D") {
                    webapi.safeAjax({
                        type: "DELETE",
                        url: "/_api/contacts(" + globalArray[i].id + ")",
                        contentType: "application/json",
                        success: function(res) {
                            document.getElementById("processingMsg").innerHTML = "Records deleted successfully. Refresh the page.";
                        }
                    });
                }
            } catch (e) {
                alert(e.message);
            }
        }
    }
}

function create() {
    var fname = prompt("Please enter your first name", "First Name");
    var lname = prompt("Please enter your last name", "Last Name");
    var email = prompt("Please enter your email", "Email");
    var phone = prompt("Please enter your phone number", "Phone Number");
    var recordObj = {
        "firstname": fname,
        "lastname": lname,
        "emailaddress1": email,
        "telephone1": phone
    };
    document.getElementById("processingMsg").innerHTML = "Creating record...";
    webapi.safeAjax({
        type: "POST",
        url: "/_api/contacts",
        contentType: "application/json",
        data: JSON.stringify(recordObj),
        success: function(res, status, xhr) {
            document.getElementById("processingMsg").innerHTML = "Records created successfully. Refresh the page. ID:" + xhr.getResponseHeader("entityid");
        }
    });
}
$(document).ready(function() {
    $('#checkedAll').on('click', function() {
        if (this.checked) {
            $('.contactIDs').each(function() {
                this.checked = true;
                $(this).parent().parent().css({
                    "color": "red",
                    "background-color": "#faffd6"
                });
            });
        } else {
            $('.contactIDs').each(function() {
                this.checked = false;
                $(this).parent().parent().css({
                    "color": "black",
                    "background-color": "#ffffff"
                });
            });
        }
    });
    $('.contactIDs').on('click', function() {
        if ($('.contactIDs:checked').length == $('.contactIDs').length) {
            $('#checkedAll').prop('checked', true);
            $('.contactIDs').each(function() {
                $(this).parent().parent().css({
                    "color": "red",
                    "background-color": "#faffd6"
                });
            });
            $(this).parent().parent().css({
                "color": "black",
                "background-color": "#ffffff"
            });
        } else {
            $('#checkedAll').prop('checked', false);
            $(this).parent().parent().css({
                "color": "black",
                "background-color": "#ffffff"
            });
        }
    });
});
You can enroll now !We are giving 30% discount on our Internship Program

Don’t miss the chance to participate in the upcoming Internship Program which will be done using Microsoft Dot Net Web Development Full Stack Technology. The new batch will be starting from May 20, 2024.  We will have most experienced trainers for you to successfully complete the internship with live project experience.

Why to choose Our Internship Program?

Industry-Relevant Projects
Tailored Assignments: We offer projects that align with your academic background and career aspirations.
Real-World Challenges: Tackle industry-specific problems and contribute to meaningful projects that make a difference.

Professional Mentorship
Guidance from Experts: Benefit from one-on-one mentorship from seasoned professionals in your field.
Career Development Workshops: Participate in workshops that focus on resume building, interview skills, and career planning.

Networking Opportunities
Connect with Industry Leaders: Build relationships with professionals and expand your professional network.
Peer Interaction: Collaborate with fellow interns and exchange ideas, fostering a supportive and collaborative environment.

Skill Enhancement
Hands-On Experience: Gain practical skills and learn new technologies through project-based learning.
Soft Skills Development: Enhance communication, teamwork, and problem-solving skills essential for career success.

Free Demo Class Available