Friday, March 1, 2013

How to handle SharePoint Poup Close event and return values in Parent Page(Very Basic ).

Code to insert a Popup in any SharePoint Product, In the first page we need to add this code :

function openPopup()
{
var options = SP.UI.$create_DialogOptions();

options.width = 900;
options.height = 600;
options.resizable = 1;
options.scroll = 1;
options.url = 'pageURL';
options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
if(SP.UI.ModalDialog.showModalDialog(options)) {
var y = $(window).scrollTop();
        var boxBorder = $(window).height() - $(".ms-dlgContent").height();
        y = y + boxBorder / 2;
        $(".ms-dlgContent").css({ position: 'absolute', top: y });
}
}

function CloseCallback(result, target)
{
 if(result == SP.UI.DialogResult.OK) {
       alert('
Value got from POPUP on OK : ' +target);
           }
    if(result == SP.UI.DialogResult.cancel) {    

       alert('Value got from POPUP on Cancel : ' +target);
        } 

}


On the PopUp Page we need to put these two code on the events we want to Close our popup as per our need of Cancel & OK handling (Such as a button click or any event) :

 SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, 'Value return to the Parent Page on OK');

 SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.Cancel, 'Value return to the Parent Page on Cancel');

Very basic and simple:)




How to set the last created item ID in SharePoint through client side coding and then get it populatd in Parent Page on PopUp Close using OOB save.

I have a new list form in which I need to submit items on 3 SharePoint Lists (No. does not matter much actually) and then populate these newly created Items ID (for current user only, as there may be so many users are accessing it on same time) on this new form. So I have done it in this way only for 1 list:

a.) Edit current list new form in Designer and then add a link on current page to open list new form. Below piece of code will open another list new form in Popup Window : :

<a href="javascript:CreateNew();" id="hypCreateNew" ><b>Create NewItem in list 2 and Populate ID</b></a>

function CreateNew()
{
var options = SP.UI.$create_DialogOptions();options.width = 900;
options.height = 600;
options.resizable = 1;
options.scroll = 1;
options.url = '/site1/Lists/List1/CustomNewForm.aspx';
options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
if(SP.UI.ModalDialog.showModalDialog(options)) {
var y = $(window).scrollTop();
        var boxBorder = $(window).height() - $(".ms-dlgContent").height();
        y = y + boxBorder / 2;
        $(".ms-dlgContent").css({ position: 'absolute', top: y });
}

}

Highlighted code set New Open Popup in the center of the page.

b.) Now in List2 CustomNewForm.aspx we need to comment default button and then add this code :

<input type="button" id="PopUPSave" value="Save" name="btnPopUPSave" onclick="javascript: {ddwrt:GenFireServerEvent('__commit;__redirect={/site1/SitePages/Redirect.aspx}')}" style="width: 200px" />

c.)  We need to add a new Page in Site Pages with Redirect.aspx (this can be any page I used a site page). On click of save we will redirect our page to this page and here we will place a single line of code :

<script type="text/javascript" src="/_layouts/jshelperlibs/jquery/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
if(window.frameElement!=null)
{
window.frameElement.commonModalDialogClose(1, 1);
}
});

Highlighted code will close opened Popup with OK result, will explain later.

This Redirect.aspx will give us this functionality to use OOB save functionality of list with our handling of Popup Close.

d.) Now In our List1 parent page we need to add these code :

function CloseCallback(result, target)
{
       if(result == SP.UI.DialogResult.OK) {
          
retrieveListItemsList1();
           }
    if(result == SP.UI.DialogResult.cancel) {   
        } 
}

As we supplied (1,1) in Redirect.aspx window.frameElement.commonModalDialogClose(1, 1); on popup Svae Click it will always call this method retrieveListItemsMPMIssue(); which is within if(result == SP.UI.DialogResult.OK).

e.) We will write body of this method to get item from list2 , using below code :




function retrieveListItemsList1() {
var currentUser = $().SPServices.SPGetCurrentUser({
  fieldName: "ID",
  fieldNames: {},     // Added in v0.7.2 to allow multiple columns
  debug: false
  });

    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('List2');
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query><Where><And><IsNotNull><FieldRef Name=\'ID\' /></IsNotNull><Eq><FieldRef Name=\'Editor\' LookupId=\'True\'  /><Value Type=\'Lookup\'>'+currentUser+'</Value></Eq></And></Where><OrderBy><FieldRef Name=\'ID\' Ascending=\'False\' /></OrderBy></Query><RowLimit>1</RowLimit></View>');
        this.collListItem = oList.getItems(camlQuery);
       
    clientContext.load(collListItem);
       
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));       
       
}


var listItemID= '';

function onQuerySucceeded(sender, args) {

    var listItemEnumerator = collListItem.getEnumerator();
       
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
       
listItemID = oListItem.get_id();    }
        $("input[title='List2 ID']").val(
listItemID);
        $("input[title='
List2 ID']").attr("disabled", "true");
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}


Highlighted Block 1 : This code will give you the current user name as ID which we will use in our caml Query to get ID. It used SPServices, you can do it through COM but that will be a lot of coding.

Highlighted Block 2 : In this query we will get all item created by this user in descending order of modified (which will be same as created at the time of creation) and then get Very first ID by Row Limit. So we will get latest ID.



So above code will populate ID in needed place, here its a control with Title List2 ID.