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...

Create bulk Sub site Using power shell script using custom SharePoint template

#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://xxxx.sharepoint.com/sites/sPOTest2/" $Context = New-Object Microsoft.SharePoint.Client.ClientContext($Site) $Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username,$Password) $Context.Credentials = $Creds $csvLocation = "C:\Users\AA82211\Desktop\PS_SiteCollectionsToCreate.csv" $csv = Import-Csv $csvLocation #List Custom Templates $Templates = $Context.Site.GetWebTemplates("1033","0") $Context.Load($Templates) $Context.ExecuteQuery() $...

Business-critical processes with SharePoint and SQL

SharePoint 2010 provides the ability to connect to backend business systems, surface business data in SharePoint and make it accessible by, and useful to, employees across the organization. Almost every company of significant size uses ERP and CRM solutions to run core business processes. Over time, companies have developed detailed practices around using such systems to support vertical disciplines within the organization (e.g. product planning, financial performance management, supply-chain management, etc.),  yet challenges remain with regard to driving visibility and collaboration, based on business data, across different disciplines and teams. These challenges stem from the fact that only a fraction of employees are licensed and trained to use those backend systems, and from the high cost and complexity of integrating such systems across different functions and teams. With SharePoint and SQL, once the relevant business data is surfaced in an enterprise-wide...