1

In the "Created By"List Column I need to search if Current login user is present or not using Java Script. How can I achieve that.

6
  • Can you explain a bit more on what you want to achieve? SharePoint without JavaScript does not do much. It won't display Views so created by is never displayed/processed front-end side. Commented Oct 19, 2015 at 8:54
  • I have list where I need to update list items based on logged in user. So First I need to check who is logged in user (I did) now I want to check if that user name presents in that Particular List's created By column.so that I can take the Item Id and update the value. Commented Oct 19, 2015 at 8:57
  • Where do you want to execute this code? In the List View? Commented Oct 19, 2015 at 9:33
  • You need to check it for all items or a particular item? Commented Oct 19, 2015 at 9:40
  • Need to check the items for a particular item i.e. created by Commented Oct 19, 2015 at 9:44

3 Answers 3

2

So you need to check if

Created By == Current User

You can find current user by following line of code

var currentUserId = _spPageContextInfo.userId

Now filter items based on currentUserId. You have to make a GET request in the following URL

/_api/web/lists/GetByTitle('List Name')/Items?$filter=AuthorId eq currentUserId

Full code should look like following

    function currentUsersItems(listName, currentUserId) {
    var url = "/_api/web/lists/GetByTitle('" + listName + "')/Items?$filter=AuthorId eq " + currentUserId + "";
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + url,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function(data) {
            var currentUsersItems = data.d.results;
        },
        error: function(error) {
            alert(JSON.stringify(error));
        }
    });
}
2
  • He wants it for all items. So I think it should be /items?$filter=AuthorId eq <userID>.
    – Akhoy
    Commented Oct 19, 2015 at 9:45
  • Thanks @Akhoy. His question and comments messed me up. I am giving a update Commented Oct 19, 2015 at 9:49
2

Provided you are executing this in a VIEW with the Created By column displayed all information is available in the ctx object and _spPageContextInfo and you do not need any round-trips back to the server

proof of concept code, run from Dev Console

ctx.ListData.Row.forEach(function(row){
   console.log(row);
   var user=row.Author[0];
   if(user.id===_spPageContextInfo.userId){ 
       console.info('match',user.title,'item ID',row.ID)
   };
});

You can use CSR or other coding techniques to process per ListItem

PS. I presume you know you can filter a View on the Current User with:

0

Its a 2 step work.

First is to get the current logged in user and store it in variable

// Getting current user
//
var currentUser = null;
function getCurrentUser() {
    try {
        var clientContext = new SP.ClientContext.get_current();
        var tempcurrentUser = clientContext.get_web().get_currentUser();
        clientContext.load(tempcurrentUser); 
        clientContext.executeQueryAsync(function () {
            var index = tempcurrentUser.get_loginName().indexOf('|') + 1;
            currentUser = tempcurrentUser.get_loginName().substring(index);

        }, 
        function () {
            alert("Error");
        });
    }
    catch (err) {
        alert("Error");
    }
}

Second is to query SharePoint List with item Id and check if the current user is the one in created by field value.

//Get the list item whose Id is 4. Note that this is the ID of the item in the list, not a reference to its position in the collection.
var itemId = 4;   
var targetListItem;

function runCode() {
  var clientContext = new SP.ClientContext(); 
  var targetList = clientContext.get_web().get_lists().getByTitle('YourListName');
  targetListItem = targetList.getItemById(itemId);
  clientContext.load(targetListItem, 'Author');
  clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {

    if(currentUser == targetListItem.get_item('Author') {
        // Its checked that current user is the creator of this item
        // Here you write code to update your item
    }

}

function onQueryFailed(sender, args) {
  alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
2
  • But here I need to iterate every author name in the list to match with the login user name ... Commented Oct 19, 2015 at 9:58
  • You can use caml query where createdby=currentUser. With the help of this query you will get all items whose author is current user example you get 5 items. Then you update those 5 items.
    – Asad Refai
    Commented Oct 19, 2015 at 10:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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