none
How to get items from SharePoint by Current User via REST or JSOM? RRS feed

  • Question

  • I am currently able to get the current user:

        var currentUser;
        function init() {
            this.clientContext = new SP.ClientContext.get_current();
            this.oWeb = clientContext.get_web();
            currentUser = this.oWeb.get_currentUser();
            this.clientContext.load(currentUser);
            this.clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
        }
    
        function onQuerySucceeded() {
            console.log(currentUser.get_loginName());
        }
    
        function onQueryFailed(sender, args) {
            console.log('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
        }


    No i need to query the mutli user field in my list for all items where my current user is part of the people field. I dont know how to query for this.

    Can someone help me out?

    Thursday, September 22, 2016 8:37 AM

Answers

  • Hi,

    We can use REST API to achieve it. In my test environment, my multiple user filed internal name is "PeopleField", and list name is "CustomList", please modify the code below. To get current user id, we just use _spPageContextInfo.userId to achieve it.

    <script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function () {
     var siteURL = _spPageContextInfo.webAbsoluteUrl;
     var listname = "CustomList";
     var currentUserId=_spPageContextInfo.userId;
     var url = siteURL + "/_api/web/lists/getbytitle('" + listname + "')/items?$select=Title,PeopleField/ID&$filter=substringof('"+currentUserId+"',PeopleField/ID)&$expand=PeopleField/ID";
     $.ajax({
    	 url: url,
    	 method: "GET",
    	 headers: { "Accept": "application/json; odata=verbose" },
    	 success: function (data) {	 	 
    		var items = data.d.results;
    		for(var i = 0; i < items.length;i++) {			 
    			var item=items[i];
    			console.log(item.Title);
    		}		
    	 },
    	 error: function (data) {		
    	 }
     });
    });
    </script>

    More information:

    https://www.plusconsulting.com/blog/2013/05/crud-on-list-items-using-rest-services-jquery/

    http://www.codeproject.com/Articles/990131/CRUD-Operation-to-List-Using-SharePoint-Rest-API

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    • Marked as answer by BOG's Lab Friday, September 23, 2016 7:07 AM
    Friday, September 23, 2016 2:32 AM
    Moderator

All replies

  • Try to use CAML query with includes statement.

    http://sharepoint.stackexchange.com/questions/26473/caml-query-for-field-of-type-person-or-group-which-allows-multiple-selections

    Example:

        <Where>
         <Includes>
          <FieldRef Name='AssignedTo' LookupId='TRUE' />
          <Value Type='Integer'>" + currentUserId+"</Value>
         </Includes>
        </Where>"


    ndeykin

    Thursday, September 22, 2016 8:51 AM
  • Ok, thank you. But how can i use a CAML on client side within Javascript? Is this possible? I think CAML Queries can be used with SPQuery on Server Object Model.
    Thursday, September 22, 2016 9:25 AM
  • var clientContext = SP.ClientContext.get_current();
            var hostWebContext = new SP.AppContextSite(clientContext, CO.Configs.SPHostUrl);
            var list = hostWebContext.get_web().get_lists().getByTitle("Homework");
            //var list = clientContext.get_web().get_lists().getByTitle("Homework");
            var query = new SP.CamlQuery();
            query.set_viewXml(
                "<View>"
                + "<Query>"
                + " <OrderBy>"
                + "     <FieldRef Name='Modified' Ascending='False'/>"
                + "     <FieldRef Name='Title' Ascending='True'/>"
                + " </OrderBy>"
                + " <Where>"
                + "     <Geq>"
                + "         <FieldRef Name='Modified'/>"
                + "         <Value Type='DateTime'><Today OffsetDays='-7'/></Value>"
                + "     </Geq>"
                + " </Where>"
                + "</Query>"
                + "<ViewFields>"
                + " <FieldRef Name='Title'/>"
                + " <FieldRef Name='Modified'/>"
                + " <FieldRef Name='Editor'/>"
                + " <FieldRef Name='FileRef'/>"
                + " <FieldRef Name='FileLeafRef'/>"
                + " <FieldRef Name='File_x0020_Size'/>"
                + "</ViewFields>"
                + "<RowLimit>100</RowLimit>"
                + "</View>"
                );
            self._pendingItems = list.getItems(query);
            clientContext.load(self._pendingItems);

    ndeykin

    Thursday, September 22, 2016 9:37 AM
  • Sorry, use this instead. Previous one is for SharePoint app model.

    var clientContext = SP.ClientContext.get_current();
    var list = clientContext.get_web().get_lists().getByTitle("Homework");
    var query = new SP.CamlQuery();
     query.set_viewXml(

    .............


    ndeykin


    Thursday, September 22, 2016 9:47 AM
  • Hi,

    We can use REST API to achieve it. In my test environment, my multiple user filed internal name is "PeopleField", and list name is "CustomList", please modify the code below. To get current user id, we just use _spPageContextInfo.userId to achieve it.

    <script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function () {
     var siteURL = _spPageContextInfo.webAbsoluteUrl;
     var listname = "CustomList";
     var currentUserId=_spPageContextInfo.userId;
     var url = siteURL + "/_api/web/lists/getbytitle('" + listname + "')/items?$select=Title,PeopleField/ID&$filter=substringof('"+currentUserId+"',PeopleField/ID)&$expand=PeopleField/ID";
     $.ajax({
    	 url: url,
    	 method: "GET",
    	 headers: { "Accept": "application/json; odata=verbose" },
    	 success: function (data) {	 	 
    		var items = data.d.results;
    		for(var i = 0; i < items.length;i++) {			 
    			var item=items[i];
    			console.log(item.Title);
    		}		
    	 },
    	 error: function (data) {		
    	 }
     });
    });
    </script>

    More information:

    https://www.plusconsulting.com/blog/2013/05/crud-on-list-items-using-rest-services-jquery/

    http://www.codeproject.com/Articles/990131/CRUD-Operation-to-List-Using-SharePoint-Rest-API

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    • Marked as answer by BOG's Lab Friday, September 23, 2016 7:07 AM
    Friday, September 23, 2016 2:32 AM
    Moderator
  • This is a requirement which you will get in all the business requirement in the SharePoint client-side technologies. You can follow the below tutorial: I have explained various approach to filter list items based on created by logged in user in SharePoint online list using Rest API.

    Rest API filter list items created by logged in user SharePoint Online/2013/2016

    Hope this will be helpful to you.

    * This is an old forum post, but still lots of people are searching on this topic.


    Many Thanks,
    Bijay Kumar
    EnjoySharePoint.com | SharePointSky.com | TSInfoTechnologies.com

    Bijay Kumar MVP

    Sunday, March 24, 2019 2:35 PM