Domanda

I have a SharePoint 2013 custom list and a requirement to load the last list item where Status = New. I first tried SPGetLastItemID with a CAML query filter - however, that method only returns items for the current user, and I need the last item where Status = New for ALL items/users.

For some reason I can't seem to get this working (no alert box):

var LastID;
function QueryLastNewStatusItem() {
    var clientContext = new SP.ClientContext();
    var List = clientContext.get_web().get_lists().getByTitle('Tracker');
    var query = new SP.CamlQuery();
    var textCaml ="
        <View> 
        <RowLimit>1</RowLimit> 
        <Query> 
            <OrderBy> 
            <FieldRef Name='ID' Ascending='False' /> 
            </OrderBy>
            <Where>
            <Eq>
                <FieldRef Name='Status' />
                <Value Type='Text'>New</Value>
            </Eq>
        </Where> 
        </Query>
        </View>";
    query.set_viewXml(textCaml);
    var item = List.getItems(query);
    context.load(item);
    LastID = GetItemID(item);
    alert(LastID);
}   

I am beginner level with JavaScript and pretty new to CAML queries. I did use internal names for FieldRef Names within the query and made sure that the function is firing.

È stato utile?

Soluzione 2

I removed the step of getting the item's ID since I can pull what I need from that item once it's loaded without having the ID, I also changed the format of the query (if writing it as multi-line each line needs to be in quotes with a "+" on the end. I also inserted the query directly into query.set_viewXml() rather than creating a variable for it. Now it's working great!

function QueryLastNewStatusItem() {
    var clientContext = new SP.ClientContext();
    var List = clientContext.get_web().get_lists().getByTitle('Tracker');
    var query = new SP.CamlQuery();
    query.set_viewXml("<View><RowLimit>1</RowLimit><Query><OrderBy><FieldRef Name='ID' Ascending='False' /></OrderBy><Where><Eq><FieldRef Name='Status' /><Value Type='Text'>New</Value></Eq></Where></Query></View>");
    this.collListItem = List.getItems(query);
    clientContext.load(collListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));        
}

function onQuerySucceeded() {
    alert("query suceeded");
}

function onQueryFailed() {
    alert("query failed");
}

Altri suggerimenti

Try using below query on Status field:

<Where>
  <Eq>
     <FieldRef Name='Status' />
     <Value Type='Choice'>New</Value>
  </Eq>
</Where>

Note: Assuming that Status field is a Choice field.


I would recommend you to utilize the tool that will help you build your CAML Queries easily, for example U2U Caml Query Builder

enter image description here

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a sharepoint.stackexchange
scroll top