Skip to main content

SurveyJS and PowerApps Portals [Part 3]

 

Web Template implementation- to generate and capture Assessment Forms from Dynamics Table created in the 2nd part of this topic.

  


Go to the Web Template created in the 1st part of this topic and paste the below snippet into it

<script>
    (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)
    </script>
    <script src="https://unpkg.com/jquery"></script>
    <script src="https://unpkg.com/browse/survey-jquery@1.9.79/survey.jquery.js"></script>
    <link href="https://unpkg.com/survey-jquery/modern.min.css" type="text/css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/survey-jquery/1.9.76/survey.jquery.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <form>
      <div class="loader" id="page-loader"></div>
  <div class="form-group">
    <div id="surveyElement"></div>
  </div>
  <div class="form-group">
   <div class="alert alert-info text-center scrolling-text" role="alert" id="save-info">
    </div>
  </div>
</form>
   
<script type="text/javascript">
var survey;
var formID = "{{request.params.id}}";
$(document).ready(function()
{  
    getSurveyData();
});
function getSurveyData()
{
    $('#page-loader').show();
    webapi.safeAjax({
        type: "GET",
        url: "/_api/cr84c_formspayload("+formID+")?$select=cr84c_surveyjspayload,cr84c_surveyresponseobject",
        contentType: "application/json",
        success: function (data, textStatus, xhr)
        {
            var result = data;
            console.log(result);
            var cr84c_payload = result["cr84c_surveyjspayload"]; // Multiline Text
            var surveyJSON = JSON.parse(cr84c_payload);
            var storedSurveyResponse = result["cr84c_surveyjspayload"];
            storedSurveyResponse = JSON.parse(storedSurveyResponse);
            survey = new Survey.Model(surveyJSON);
            survey.data = storedSurveyResponse;

            survey.onPartialSend.add(function(sender)
            {
                saveSurveyData(sender);
            });
            survey.sendResultOnPageNext = true;
            $("#surveyElement").Survey({model: survey});
           
            // Render the SurveyJS object to the page
            survey.render("surveyElement");
            $('#page-loader').hide();
            $('#save-info').show();
            $("#save-info").text("");
            var message = "Your responses would be saved on navigating through pages while not completing all required fields. In order to submit/complete the form all the required fields must be filled.";
            $("#save-info").text(message);
            survey.onComplete.add((survey, options) => { registerSurveyCompleteHandler("complete") });
            survey.onPartialSend.add((survey) => { registerSurveyCompleteHandler("draft") });  
        },
        error: function (xhr, textStatus, errorThrown)
        {
            $('#page-loader').hide();
            console.log(xhr);
        }
    })
}
function registerSurveyCompleteHandler(actionType)
{
    $('#page-loader').show();
        debugger;
        var title = "dummy";
        var pages = [];
        var questionNumber = "";
        var elements = {};

        for (var i = 0; i < survey.visiblePages.length; i++)
        {
            var page = survey.visiblePages[i];
            var questions = page.questions;
           
            for (var j = 0; j < questions.length; j++)
            {
                var question = questions[j];
                questionNumber = question.name;
                elements[questionNumber] = survey.data[question.name];
            }
        }

        var record = {};
       record.cr84c_surveyresponseobject = JSON.stringify(elements); // Multiline Text

        webapi.safeAjax({
            type: "PATCH",
            contentType: "application/json",
            url: "/_api/cr84c_formspayload("+formID+")",
            data: JSON.stringify(record),
            success: function (data, textStatus, xhr)
            {
                $('#page-loader').hide();
                console.log("Record updated");
            },
            error: function (xhr, textStatus, errorThrown)
            {
                console.log(xhr);
            }
        });
}
function saveSurveyData(survey)
{
    var data = survey.data;
    data.pageNo = survey.currentPageNo;
    //window.localStorage.setItem(storageName, JSON.stringify(data));
    registerSurveyCompleteHandler("draft");
}
</script>





using the provided snippet, it renders the form as above.

When user clicks on complete, after providing the responses, the responses are stored under "SurveyJS Response" column created in the back end.

Comments

Popular posts from this blog

Validate an email input in a Canvas Application | PowerApps

Validate an email input in a Canvas Application | PowerApps In this post let us see, how to Validate an email input in a Canvas Application UI Validations helps us to ensure, valid data is received from the End User to complete an operation helps end user to provide right information the validation action depends on the type of the input control for Text Input Control - mostly we go with "OnChange" for check box control - "OnCheck and On uncheck" for Drop Down and Combo Box Controls - "OnChange" or "OnSelect" etc., Now, let us see how can we validate an email input, a phone number input and a name input. How to validate an email input value is valid? We can leverage "Regex" (Regular Expressions) to valid user inputs. Let us consider the Email Input Control Name as -  txtEmail.Text. OnChange of this Control let us i...

Success confirmation on a record submission - Canvas Application

In this post let us see, how to show a successfully submitted record's data back on to the form, as a confirmation. Take two screens  Home Screen Success Screen On Home Screen: Take a Form Control on the Home Screen and map it to respective entity. In this post we are mapping it to Registrations entity. Take a Button Control and input the below expression, to create records into Registrations Entity. SubmitForm( frmRegistration ) Now, let us implement how to redirect the user to Success Message screen to successful record submission. In order to achieve this, we are going to make use of one of the Form Control's properties - OnSuccess. So, OnSuccess we are going to implement Success Screen navigation as below Navigate(' Success Screen ')   Success Screen Take a label to show - success message, as below "Registration was successful. Registration Id: " & frmRegistration .LastSubmit.'Registration Number' LastSubmit  property of a From Control helps u...

Get old SharePoint Files using Power Automate efficiently

In this post, let us see how can we get the old files from a SharePoint Folder using Power Automate. In this example, I am considering a simple approach and this can be extended based on the requirement. To ensure the Power Automate is simple, efficient and the performance is optimized - we are not using ForEach control to loop through and identify old file or item.  We use " Send an HTTP request to SharePoint " in the Power Automate and query the data using OData filters and order by.  The idea here for the faster retrieval - selecting only a required set of fields from the file. Steps to achieve this: Login to https:make.powerautomate.com . New Cloud Flow -> Scheduled Or Instant (based on the requirement). (Configure the Start Date and Time. For repeat, every, configure the seconds/ minutes/  hours/ day/ week/ month) Click on Create Button. Click + icon to add new action. Search for SharePoint and select  " Send an HTTP request to SharePoint " Select the re...