0

I'm having a bit of trouble creating a reusable function to get various data from SharePoint lists. I'm at a loss as to what to do - everything I've read/searched for implies this code should work, but it's not.

I have the following function:

    // Pulls data from a SharePoint list and updates the target element
    // Usage:
    // Input:
    //              listName: SharePoint list name we're looking up
    //              camlXML: XML for the CAML filter we use
    //              fieldName:
    //              context:
    //              element:

    function getSPListData(listName, camlXML, fieldName, context, element) {
            var clientContext = context;

            var SPList = clientContext.get_web().get_lists().getByTitle(listName);

            var camlQuery = new SP.CamlQuery();
            camlQuery.set_viewXml(camlXML);

            var collListItem = SPList.getItems(camlQuery);

            var includeStatement = "Include(" + fieldName + ")";

            clientContext.load(collListItem, includeStatement);
            var newText = "";
            clientContext.executeQueryAsync(
                    function (sender, args) {
                            var listItemEnumerator = collListItem.getEnumerator();

                            while (listItemEnumerator.moveNext()) {
                                    var oListItem = listItemEnumerator.get_current();
                                    newText = newText + oListItem.get_item(fieldName);
                            };
                            element.text(newText);
                    },
                    function (sender, args) {
                            element.text("Error -> getSPListData -> clientContext.executeQueryAsync request failed");
                    }
            );
    };

I have another function which I'm using to create elements within a list. This work - I'm sure there's a way to do it better because of my ignorance with the SharePoint API.

    function linkIDs(context, SID1, field1, SID2, field2, list) {
            //var clientContext = new SP.ClientContext.get_current();
            var clientContext = context;

            var oList = clientContext.get_web().get_lists().getByTitle(list);
            var item = new SP.ListItemCreationInformation();
            var oListItem = oList.addItem(item);

            var Item1LookupField = new SP.FieldLookupValue();
            var Item2LookupField = new SP.FieldLookupValue();

            Item1LookupField.set_lookupId(SID1);
            oListItem.set_item(field1, Item1LookupField);

            Item2LookupField.set_lookupId(SID2);
            oListItem.set_item(field2, Item2LookupField);

            oListItem.update();

            clientContext.load(oListItem);

            return clientContext;
    };
  • What is not working? Did you debug the code and check? Also check F12 for the error. – Akhoy Sep 19 '15 at 14:44
0

I figured out a decent way to accomplish this, however I don't use CAML, instead I rely on the REST API.

// Queries a SharePoint list using the REST API to retrieve items.
// Remember - we're dealing with asynchronous queries
// Input fields use syntax here: 
// https://msdn.microsoft.com/en-us/library/ff798339.aspx
// Input:
//      listName: SharePoint listname
//      queryItem: List fields
//      queryFilter: Any filters
//      sortMethod: Sort order
//      expandParams: Field expansion params
// Returns:
//      AJAX Object
function getListItem(listName, queryItem, queryFilter, sortMethod, expandParams) {
    /*
        /(.*?)SitePages.+/
            1st Capturing group (.*?)
                .*? matches any character (except newline)
                    Quantifier: *? Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
                SitePages matches the characters SitePages literally (case sensitive)
                .+ matches any character (except newline)
                    Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
    */
    var URL = $(location).attr("href").replace(/(.*?)SitePages.+/g, "$1") + "_vti_bin/listdata.svc/" + listName;

    if (queryItem || queryFilter || sortMethod) {
        URL = URL + "?";
    }

    if (queryItem) {
        URL = URL + "$select=" + queryItem;
    }

    if (queryFilter) {
        if (queryItem) {
            URL = URL + "&$filter=" + queryFilter;
        } else {
            URL = URL + "$filter=" + queryFilter;
        }
    }

    if (sortMethod) {
        if (queryItem || queryFilter) {
            URL = URL + "&$orderby=" + sortMethod;
        } else {
            URL = URL + "$orderby=" + sortMethod;
        }
    }

    // Assume if we have expandParams it's not the first element
    if (expandParams) {
        URL = URL + "&$expand=" + expandParams;
    }

    var ajaxCall = $.ajax({
        url: URL,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        async: true,
        cache: true
    });

    return ajaxCall;
}

You then call this function like:

    var ID = IDfromSomewhere;
    var listName = "testList";
    var fieldName = "field1, field2, field3";
    var queryString = "field1 eq '" + ID + "'";
    var sortMethod = "field1 asc, field2 asc";

    var query = getListItem(listName, fieldName, queryString, sortMethod);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.