0

So for the whole day I've been trying to create a select2 javascript selectbox that would display certain list elements using API. I have found a couple of articles such as Understanding SP Rest API or SP Jslink select2 and all i was able to come up so far was:

    $('.js-data-example-ajax').select2({

    id: function(e) {
        return (e.id ? e.id : e.ID);
    },
    ajax:  {   url: "mydomain/_api/web/lists/getbytitle('S')/Items?$select=Title",
    type: "GET",     
    headers: {
        "accept": "application/json;odata=verbose",
    },
    dataType: 'json',


width: '400px',
});

Using some developer tools i have found that adress it is trying to access is: /_api/search/?term=value+&_type=query&q=value+ where value is what was entered into the search box. This is definitely different to what was described in the first article as the correct address. Can someone please just point me in the right direction as to how should I approach this problem and make select2 work with Sharepoint's list. Thanks.

  • 2
    What happens when you directly paste this in browser window mydomain/_api/web/lists/getbytitle('S')/Items?$select=Title and hit enter – Arsalan Adam Khatri Nov 21 '17 at 15:14
  • Hey, thanks for trying to help! i.imgur.com/FZcSLAw.png That happens. I get the list of all elements that shows their Title. – Kloggy Nov 21 '17 at 21:59
  • 1
    That means your REST API is working fine, can you make it work outside SharePoint, for example in a separate HTML file. – Arsalan Adam Khatri Nov 23 '17 at 5:42
0

Okay i think i figured that out. The sharepoint API does not work with query parameters provided by select2. So essentialy you need to query for the whole list first and then in processResults function convert them into a format that is acceptable by select2 like so:

{
  "results": [
    {
      "id": 1,
      "text": "Option 1"
    },
}

I completely changed the way I am doing it and unfortunately cannot find a function I used to make it work now, but it is a simple one that just goes through all displayed elements by the API request and pushes them into the object that can be used as data source for select2.

EDIT: If i remember correctly function was like so:

 processResults: function (data) {
          new_data = [];
        data.items.forEach(function(i, item) {
          new_data.push({
            id: i.name,
            text: i.name
          }); });
return {
          results: new_data
        };
}

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.