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

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

Powershell Script to Restrict Group Creation on Office 365

$GroupName = "<SecurityGroupName>" $AllowGroupCreation = "False" Connect-AzureAD $settingsObjectID = (Get-AzureADDirectorySetting | Where-object -Property Displayname -Value "Group.Unified" -EQ).id if(!$settingsObjectID) { $template = Get-AzureADDirectorySettingTemplate | Where-object {$_.displayname -eq "group.unified"}     $settingsCopy = $template.CreateDirectorySetting()     New-AzureADDirectorySetting -DirectorySetting $settingsCopy     $settingsObjectID = (Get-AzureADDirectorySetting | Where-object -Property Displayname -Value "Group.Unified" -EQ).id } $settingsCopy = Get-AzureADDirectorySetting -Id $settingsObjectID $settingsCopy["EnableGroupCreation"] = $AllowGroupCreation if($GroupName) { $settingsCopy["GroupCreationAllowedGroupId"] = (Get-AzureADGroup -SearchString $GroupName).objectid }  else { $settingsCopy["GroupCreationAllowedGroupId"] = $GroupName } Set-AzureADDirectorySetting -Id $...

Custom Actions Event Receiver

using System; using System.Collections.ObjectModel; using System.IO; using System.Runtime.InteropServices; using System.Xml; using Microsoft.SharePoint; using Microsoft.SharePoint.Administration; using Nintex.Workflow; using Nintex.Workflow.Administration; using Nintex.Workflow.Common; using System.Reflection; namespace CFSP.CustomActions.Features.WebApplication___Custom_Actions {     [Guid("07607091-449b-422b-94e4-84e6d863eb9e")]     public class WebApplication___Custom_ActionsEventReceiver : SPFeatureReceiver     {         #region Events         public override void FeatureActivated(SPFeatureReceiverProperties properties)         {             SPWebApplication parent = (SPWebApplication) properties.Feature.Parent;             AddCustomAction(parent, properties, "ReadFromPropertyBagAction.nwa");     ...