Thursday, 23 February 2017

Conditionally Show/Hide and Require SharePoint fields with JavaScript

Conditionally Show/Hide and Require SharePoint fields with JavaScript

In my last project I worked on DMS system based on SharePoint Server 2016 and had a very common requirement for the document forms. The requirement was to have Document Status field, Approval Reason and Rejected Reason fields. It is logical to want to hide Approval Reason when the document status is Rejected or Rejected Reason when the document is Approved.The client also wanted to make the fields required when the corresponding document status is selected. 
All customizations were going to be deployed using the classic way, with farm solution. I also had Nintex Forms, but I was unable to use it in this case due to other technical constraints.
That's why I decided to solve this requirement using JQuery and JavaScript script that are deployed with the WSP solution and included in the mater page.
The end result was pretty good and this is why I decided to share the script and a way to safely deploy it in SharePoint Online without the need to edit the master page or the list forms. The script is really simple and can be used/deployed as it is or with minor changes by person with moderate JavaScript experience.
Few notes on the SPO environment that was used. There are 3 custom site columns with following Title, InternalNames and Type: 
- Title: Document Status, InternalName: DocumentStatus, Choice, radio buttons
- Title: Approval Reason, InternalName: ApprovalReason, Multi-line text, Not required by definition
- Title: Rejected Reason, InternalName: RejectedReason, Multi-line text, Not required by definition

You can see the script below:

// http://www.sptrenches.com/2017/01/conditionally-showhide-and-require.html
function showOrHideFields() {
switch ($('input[type=radio][id^=DocumentStatus]:checked').val()) {
case "Rejected":
{
$("textarea[id^=RejectedReason]").closest("tr").show();
$("textarea[id^=ApprovalReason").closest("tr").hide();
break;
}
case "Approved":
{
$("textarea[id^=RejectedReason]").closest("tr").hide();
$("textarea[id^=ApprovalReason").closest("tr").show();
break;
}
default:
{
$("textarea[id^=RejectedReason]").closest("tr").hide()
$("textarea[id^=ApprovalReason").closest("tr").hide();
}
}
var viewModeStat = ($("[name^=SPBookmark_DocumentStatus]").closest("td").next("td")).text().trim();
if(viewModeStat) {
switch (viewModeStat) {
case "Rejected":
{
$("a[name=SPBookmark_RejectedReason]").closest("tr").show();
$("a[name=SPBookmark_ApprovalReason]").closest("tr").hide();
break;
}
case "Approved":
{
$("a[name=SPBookmark_RejectedReason]").closest("tr").hide();
$("a[name=SPBookmark_ApprovalReason]").closest("tr").show();
break;
}
default:
{
$("a[name=SPBookmark_RejectedReason]").closest("tr").hide()
$("a[name=SPBookmark_ApprovalReason]").closest("tr").hide();
}
}
}
}
$(function () {
showOrHideFields();
$('input[type=radio]').change(showOrHideFields);
})
function PreSaveAction() {
if (($('input[type=radio][id^=DocumentStatus]:checked').val() == "Rejected") && ($("textarea[id^=RejectedReason]").val() == "")) {
var rejField = $("textarea[id^=RejectedReason]");
var errorHtml = '<span class="ms-formvalidation"><span role="alert">Please, specify Rejected Reason*<br></span></span>';
rejField.after(errorHtml);
return false;
} else if (($('input[type=radio][id^=DocumentStatus]:checked').val() == "Approved") && ($("textarea[id^=ApprovalReason").val() == "")) {
var appField = $("textarea[id^=ApprovalReason");
var errorHtml = '<span class="ms-formvalidation"><span role="alert">Please, specify Approval Reason*<br></span></span>';
appField.after(errorHtml);
return false;
}
return true;
};
view rawShowHide.js hosted with ❤ by GitHub
There are two main functions, showOrHideFields that will be started when the page is loaded and will show or hide Approval Reason or Rejected Reason field depending on the value of the Document Status field in New,View and Edit forms. The second function is with the specific name PreSaveAction, it will be launched when Check In or Save button is clicked and will not allow the form to be saved if Approval Reason or Rejected Reason fields are empty and will pop-out an "error" message below the field, again depending on the Document Status field value.
Below you can see how the form looks like in New,Edit and View mode.

New, Edit and View forms

In order to deploy the script without modifying the forms or the master page we are going to use the SharePoint PnP PowerShell module for SharePoint Online. In order to "inject" the javascript links we are going to use Add-PnPJavaScriptLink command. In the example below I am uploading the JS file, adding ScriptLink to it and adding ScriptLink to Google hosted JQuery library.



Add-PnPFile -Path "C:\Users\Ivan\Documents\ShowHide.js" -Folder "Style Library/scripts/" `
    -Checkout -Publish -CheckInComment ""
 
Add-PnPJavaScriptLink -Name JQuery `
    -Url "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"
 
Add-PnPJavaScriptLink -Name ShowHide `
    -Url "https://mod44444.sharepoint.com/Style%20Library/scripts/ShowHide.js"


Once the commands are executed the scripts will be loaded in all classic pages in the web(default scope for this command).
Unfortunately this really useful way of injecting JavaScript will not work with the modern pages and the new Library and List experience. More info on this huge gap can be found in this post.

Monday, 20 February 2017

SharePoint Model Dialog PopUp

Example - 1

<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
//User Defined Function to Open Dialog Framework
function OpenDialog() 
{
var element = document.createElement('div');
element.innerHTML = '<html><head><style>body {background-color: yellow;}</style></head><body><input type="text" id="popupTextBox"/><table><tr><td>name</td><td>'+$('#popup').val()+'</td></tr><tr><td>name</td><td><input type="button" value="OK" onclick="SaveForm()" />&nbsp;<input type="button" value="Cancel" onclick="CancelForm()"/></td></tr></table></body></html>';
  var dialogOptions = SP.UI.$create_DialogOptions();
 dialogOptions.html=element;
  dialogOptions.title = $('#popup').val();
  dialogOptions.allowMaximize= true;
  dialogOptions.args={ arg1: 'The second argument is ', arg2: 12345 };
  dialogOptions.style='background-color:green';
  dialogOptions.width = 500; // Width of the Dialog
  dialogOptions.height = 250; // Height of the Dialog
dialogOptions.dialogReturnValueCallback=CloseCallback;
  //SP.UI.ModalDialog.showModalDialog(dialogOptions); // Open the Dialog
   SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', dialogOptions); 
  test();
 // DoSomethingWithArgs();
  return false;
  
}

// Dialog close event capture function
function CloseCallback(strReturnValue, target) 
{
  if (strReturnValue === SP.UI.DialogResult.OK) // Perform action on Ok.
    {
   alert("User clicked Ok!");
  // RefreshOnDialogClose(); it will close popup and refresh the parent page
    }
  if (strReturnValue === SP.UI.DialogResult.cancel) // Perform action on Cancel.
   {
  alert("User clicked cancel!");

   }
}
//Close popup on cancel button click

        function SaveForm() {

          SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK,'Ok Clicked');

        }

        //Commit/Refresh parent window on save button click

        function CancelForm() {
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel,'cancel Clicked');
      // window.parent.location('https://lntanjana.sharepoint.com/SitePages/WebpartDemo.aspx');// it will redirct to specifice page after closing the popup

        }
function test()
{
//alert("hi");
txtVal=$('#popup').val();
 $('#popupTextBox').val(txtVal);
}
function DoSomethingWithArgs() {

  var passedArgs = SP.UI.ModalDialog.get_childDialog().get_args(); /* get access to the passed parameters */

  alert(passedArgs.arg1 + passedArgs.arg2);

}

</script>
<input type="text" id="popup"/>
<a onclick="OpenDialog();">open dialog</a>
-----------------------------------------------------------------------------------------------------------------------
Example - 2 

<html>
<head>
<script type="text/javascript">
function init()
{
    popupWin = window.open('','popupWin','');
    popupWin.document.writeln('<html><head><title>test</title></head><body><input type="text" id="popupTextBox"/></body></html>');
    popupWin.document.close();
    popupText = popupWin.document.getElementById("popupTextBox");
    parentText = document.getElementById("parentTextBox");
    transferText();
}
function transferText()
{
    popupText.value = parentText.value
}
</script>
</head>
<body>
<input type="text" id="parentTextBox"/>
<input type="button" onclick="init();"/>
</body>
</html>

Friday, 3 February 2017

Basic list CRUD operations using REST API in SharePoint 2013

asic list CRUD operations using REST API in SharePoint 2013

Hi, today i want to share how to do basic list CURD operation using REST API.

Here the steps,

We need on SharePoint list and i have created associate list as below.


First we will design html page where we will show a button to get all items in associate list and display in a table. 

Before that we will add one content editor web part to the page. as we know that RESTAPI code will be write in script tags <script></script> and will keep the code in content editor web part.



Page looks like this.


GET ALL ITEMS:


When user click on get associate details, it will fetch the list items and display in a table format. Each row contains update and delete button. Also it will show one common button to add new item.


Here the Output.


ADD AN ITEM:

When user click on "Add Associate", it will show four text box to enter associate id, Name, number and address
It will looks as below when click on "Add associate" button.

Here the code to add new item to list.



After successfully adding new item, the table will update and will show as below.



UPDATE An ITEM:

As previously said, each row have update and delete button. Whenever user click on update button,
it will show four text boxes with the respective item at the bottom of the table.




Now user can update the details and click on "update" button, then it will update the list and refresh the table also.




And when user click on delete button in the table respective item will get delete and refresh the table.




Delete An Item:

When user clicks on delete button, it will delete the respective item from list and update the table.






Find the complete code over here