Skip to main content

Java Script code for All type columns save using SP service


/************************************************************************/
function setupAddNew(fieldTitle, listName, newFormUrl, lookupColumn, lookupColumnOwsName, multivalue) {
    var selectTD;
    if (multivalue) {
        selectTD = $("select[Title='" + fieldTitle + " selected values']").parent();
        if (selectTD.length === 0) {
            alert("SPLookupAddNew.js error --A Select control with the Title of " + fieldTitle + " selected values' was not Found");
            return;
        }
        if (selectTD.length > 1) {
            alert("SPLookupAddNew.js error--Multiple Select controls with the Title of " + fieldTitle + " selected values' were not Found");
            return;
        }
    }
    else // Single Value Select
    {
        selectTD = $("input[Title='" + fieldTitle + "']").parent();
        if (selectTD.length === 0) {
            // Don' give an error, When the user adds the 20th Item, It will switch from a select to an input tag and the add new wil appear
            //alert("A Select control with the Title of " + fieldTitle + " was not Found");
            return
        }
        if (selectTD.length > 1) {
            alert("SPLookupAddNew.js error Multiple input controls with the Title of " + fieldTitle + " were not Found")
            return;
        }
    }
    var anchortag = "<a  class='ms-addnew' onclick='AddNewLookupItem(\"" + fieldTitle + "\",\"" + newFormUrl + "\",\"" + listName + "\",\"" + lookupColumn + "\",\"" + lookupColumnOwsName + "\"," + multivalue + ");'>Add " + fieldTitle + "</a>";
    selectTD.append('&nbsp;&nbsp;<img alt="" src="/_layouts/images/caladd.gif" complete="complete"/>&nbsp;').append(anchortag);
    checkIfLIstExists(listName, newFormUrl, lookupColumn, lookupColumnOwsName);
}
function checkIfLIstExists(listName, newFormUrl, lookupColumn, lookupColumnOwsName) {
    var lookupColumnFound = false;
    $().SPServices({
        operation: "GetList",
        listName:listName,
        completefunc: function (xData, status) {
            if (status === "error") {
                alert("SPLookupAddNew.js error-- an error occurred getting the list '" + listName + "'. Status is " + xData.status + " Status Text is " + xData.statusText + ". Perhaps the List name " + listName + " is Incorrect");
            }
            else {
                $(xData.responseXML).find("Fields > Field").each(function () {
                    var $node = $(this);
                    if ($node.attr("StaticName") == lookupColumn) {
                        lookupColumnFound = true;
                    }
                });
                if (lookupColumnFound == false) {
                    var errorMessage = "SPLookupAddNew.js error-- the Lookup Column " + lookupColumn + " in list " + listName + " was not found. Valid Columns are ";
                    $(xData.responseXML).find("Fields > Field").each(function () {
                        var $node = $(this);
                        errorMessage += $node.attr("StaticName") + ", ";

                    });
                    alert(errorMessage);

                }
            }
        },
        errorfunc: function (xData, Status) {
            alert("SPLookupAddNew.js error --The List " + listName +" was not Found");
        }
    });

}
function AddNewLookupItem(fieldTitle, newFormUrl, listName, lookupColumn, lookupColumnOwsName, multivalue) {
    var siteUrl = SP.ClientContext.get_current().get_url();
    var options = SP.UI.$create_DialogOptions();
    options.title = "Add " + fieldTitle;
    options.url = siteUrl + newFormUrl;
    options.dialogReturnValueCallback = GetItemAddedCallBack(fieldTitle, listName, lookupColumn, lookupColumnOwsName, multivalue);
    SP.UI.ModalDialog.showModalDialog(options);

}
function GetItemAddedCallBack(fieldTitle, listName, lookupColumn, lookupColumnOwsName, multivalue) {
    this.fieldTitle = fieldTitle;
    this.listName = listName;
    this.lookupColumn = lookupColumn;
    this.lookupColumnOwsName = lookupColumnOwsName;
    if (multivalue) {
        return function (value, returnValue) {
            ItemAddedCallbackMultiValue(value, returnValue);
        }
    }
    else {
        return function (value, returnValue) {
            ItemAddedCallback(value, returnValue);
        }
    }
}
function ItemAddedCallback(value) {
    // if user canceled out of the add dialog
    if (value == '0') return;
    // now refresh the droopdown list of vendors-- if the Vendor List has leess than 20 Items, the dropdown list is rendered as a simple select and we use  field "vendorDropDown",
    // otherwise, it's rendered as a textbox and a hiddentextbox (with some fancy behaviors) and we use fields lookupInput and hiddenlookupInput (vendor input holds the
    // display value and HiddenlookupInput holsd the ID;
    var lastItemID = $().SPServices.SPGetLastItemId({ listName: listName });
    if (lastItemID === 0) {
        alert("SPLookupAddNew.js error--SPGetLastItemId returned 0 when trying to get the ID of the Item you just added. This can be caused by calling setupAddNew with an Invalid listName");
        return;
    }
    var lookupInput = $("input[title='" + fieldTitle + "']")[0]; // put the counterparty name here when we get it
    var hiddenlookupInputFieldName = $("input[title='" + fieldTitle + "']").attr("optHid"); // get the id of the hidden itput field
    var hiddenlookupInput = $("input[id='" + hiddenlookupInputFieldName + "']")[0]; // get the hidden input field that will hold the id of the item. This is passed back to sharepoint
    var myQuery = "<Query><Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + lastItemID + "</Value></Eq></Where></Query>";
    $().SPServices({
        operation: "GetListItems",
        async: false,
        listName: listName,
        CAMLViewFields: "<ViewFields><FieldRef Name='" + lookupColumn + "' /></ViewFields>",
        CAMLQuery: myQuery,
        completefunc: function (xData, Status) {
            $(xData.responseXML).SPFilterNode("z:row").each(function () {  //THIS IS THE SYNTAX FOR THE NEWWRE JQERY jQuery 1.7+,  with
                //$(xData.responseXML).find("[nodeName='z:row']").each(function () { //OLD VESRION
                if (!($(this).attr(lookupColumnOwsName))) {
                    alert("SPLookupAddNew.js error--In the Item Added callback the field " + lookupColumnOwsName + " was not found");
                    return;
                }
                lookupInput.value = $(this).attr(lookupColumnOwsName);
                hiddenlookupInput.value = $(this).attr("ows_ID");
                //TODO -- INSERT CALLBACK HERE IINCASE THERE ARE DEPENDANT FIELDS

            });
        }
    });
}
function ItemAddedCallbackMultiValue(value) {
    // if user canceled out of the add dialog
    if (value == '0') return;
    // get the id of the item the user just added note that spGetLastItemID gets the item added bu the CURRENT USER
    var lastItemID = $().SPServices.SPGetLastItemId({ listName: listName });
    if (lastItemID === 0) {
        alert("SPLookupAddNew.js error--SPGetLastItemId returned 0 when trying to get the ID of the Item you just added. This can be caused by calling setupAddNew with an Invalid listName");
        return;
    }
    // get the listbox on the right that holds the values the user has selected
    var selectedValueDisplay = $("select[Title='" + fieldTitle + " selected values']")[0];
    if (selectedValueDisplay !== null) {
        // Get The item the user JUST Added
        var myQuery = "<Query><Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + lastItemID + "</Value></Eq></Where></Query>";
        $().SPServices({
            operation: "GetListItems",
            async: false,
            listName: listName,
            CAMLViewFields: "<ViewFields><FieldRef Name='" + lookupColumn + "' /></ViewFields>",
            CAMLQuery: myQuery,
            completefunc: function (xData, Status) {
                // get the row returned (should only be one!)
                $(xData.responseXML).SPFilterNode("z:row").each(function () {  //THIS IS THE SYNTAX FOR THE NEWWRE JQERY jQuery 1.7+,  with
                    //$(xData.responseXML).find("[nodeName='z:row']").each(function () { //OLD VESRION
                    // add the item to the listbox on the left (the selected Values)
                    if (!($(this).attr(lookupColumnOwsName))) {
                        alert("SPLookupAddNew.js error--In the Item Added callback the field " + lookupColumnOwsName + " was not found");
                        return;
                    }
                    var newOption = new Option($(this).attr(lookupColumnOwsName), $(this).attr("ows_ID"));
                    selectedValueDisplay.options[selectedValueDisplay.length] = newOption;
                    // now find the previous Input whose name or id  ends with 'MultiLookupPicker'
                    // this contains  values that will get saved to the listitem
                    var MultiLookupPicker = $(selectedValueDisplay).closest("span").find("input:[name$='MultiLookupPicker']");
                    var s = "";
                    for (var i = 0; i < selectedValueDisplay.options.length; i++) {
                        if (s != "")
                            s = s + "|t";
                        s = s + selectedValueDisplay.options[i].value.replace("|", "||");
                        s = s + "|t";
                        s = s + selectedValueDisplay.options[i].text.replace("|", "||");
                    }
                    $(MultiLookupPicker)[0].value = s;
                });
            }
        });

    }
}



Comments

Popular posts from this blog

PowerShell For create Sub site in office 365

#Add references to SharePoint client assemblies and authenticate to Office 365 site Add-Type -Path "\Software\SharePoint 2013 Client Browser v1.7\Microsoft.SharePoint.Client.dll" Add-Type -Path "\Software\SharePoint 2013 Client Browser v1.7\Microsoft.SharePoint.Client.Runtime.dll" $Username = Read-Host -Prompt "Please enter your username" $Password = Read-Host -Prompt "Please enter your password" -AsSecureString $Site = "https://XXXXXXX.sharepoint.com/sites/Test2/" $Context = New-Object Microsoft.SharePoint.Client.ClientContext($Site) $Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username,$Password) $Context.Credentials = $Creds $csvLocation = "C:\Users\PS_SiteCollectionsToCreate.csv" $csv = Import-Csv $csvLocation #List Custom Templates $Templates = $Context.Site.GetWebTemplates("1033","0") $Context.Load($Templates) $Context.ExecuteQuery() $Templates | Whe...

SharePoint Capacity Management and Sizing Overview

Capacity management   is an ongoing process, because no implementation remains static with regard to content and usage. You need to plan for growth and change, so that your SharePoint Server 2013–based environment can continue to deliver an effective business solution. Capacity Planning  is only one part of the capacity management cycle. It is the initial set of activities that brings the design architect to the point where there is an initial architecture that the architect believes will best serve the SharePoint Server 2013 deployment. The capacity management model includes additional steps to help you validate and tune the initial architecture, and provides a feedback loop for re-planning and optimizing the production environment until it can support design goals with optimal choices of hardware, topology, and configuration. Capacity management versus capacity planning Capacity management extends the concept of capacity planning to express a cyclical appr...

Convert SharePoint Date in to ConvertDateToISO - And Use for Custom Save

-------------Code ------------------------------------------- function ConvertDateToISO(dtDate) { //************************************************* //Converts Javascript dtDate to ISO 8601 standard for compatibility with SharePoint lists //Inputs: dtDate = Javascript date format (optional) //************************************************* //alert("InISOCOnversion");   var d;   if (dtDate != null)  {      //Date value supplied           d = new Date(dtDate);   }   else  {      //No date supplied, Create new date object      d = new Date();   }   //Generate ISO 8601 date/time formatted string   var s = "";   //alert(d.getFullYear());    if(d.getFullYear)    {    //alert("FullYear");          s += d.getFullYear() + "-";     }     else     {      //alert("ge...