Solved

SharePoint CAML Query - retrieving field names

Posted on 2016-10-17
3
48 Views
Last Modified: 2016-10-19
I am trying to retrieve the columns to my list which I think works but I'm having a hard time concatenating it.  Look at line 57.  How can  I get that to work.  Thanks!
	//IIFE
	$(function() {
			retrieveListItems();
	});

 * Get the value of a querystring
 * @param  {String} field The field to get the value of
 * @param  {String} url   The URL to get the value from (optional)
 * @return {String}       The field value
 */
var getQueryString = function ( field, url ) {
    var href = url ? url : window.location.href;
    var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
    var string = reg.exec(href);
    return string ? string[1] : null;
};

	//Retrieves all list items- Will need to modify to take in query string data to pass to CAML.
	function retrieveListItems() {
		var clientContext = new SP.ClientContext();
		var oList = clientContext.get_web().get_lists().getByTitle('ParkFundingForm');
		//alert(getQueryString('Title'));
		var camlQuery = new SP.CamlQuery();
			camlQuery.set_viewXml("<View><Query>"+
					   "<Where>"+
					      "<Eq>"+
					         "<FieldRef Name='Title' />"+
					         "<Value Type='Text'>"+getQueryString('Title')+"</Value>"+
					      "</Eq>"+
					   "</Where>"+
					"</Query>"+
					"<ViewFields>"+
					   "<FieldRef Name='Title' />"+
					   "<FieldRef Name='ProjectName' />"+
					   "<FieldRef Name='PriorityNumber' />"+
					   "<FieldRef Name='ID' />"+
					   "<FieldRef Name='ParkID' />"+
					   "<FieldRef Name='ProjectNumber' />"+
					"</ViewFields></View>");
	  	
		this.collListItem = oList.getItems(camlQuery);
		
		clientContext.load(collListItem);
		
	    clientContext.executeQueryAsync(
	        Function.createDelegate(this, this.onQuerySucceeded),
	        Function.createDelegate(this, this.onQueryFailed)
	        );
	}

var listName="ParkFundingForm";
var viewName = "parkView";

getFieldNames(listName, viewName);
	/*New to make this dynamic-had to get it working first.*/
	var htmlTbl = "<div><button type='Submit'>Prioritize</button></div><table id='prioritize' class='display' cellspacing='0' width='100%'>";
	htmlTbl += "<thead>"+getFieldNames(listName, viewName)+"</thead>";
	htmlTbl += "<tbody>";

	/*Array will contain two values, item id and new priority value. */
	var items=[];

	function onQuerySucceeded(sender, args) {
		var listItemInfo = '';
		var listItemEnumerator = collListItem.getEnumerator();
		
		while (listItemEnumerator.moveNext()) {
			var oListItem = listItemEnumerator.get_current();
			
			htmlTbl += "<tr><td>"+oListItem.get_item('ID')+"</td><td data-order="+oListItem.get_item('PriorityNumber')+"> "+
			"<input type='text' name = 'rowID-"+oListItem.get_item('ID')+"' id='rowID-"+oListItem.get_item('ID')+"' data-curVal="+oListItem.get_item('PriorityNumber')+" value="+oListItem.get_item('PriorityNumber')+"></td>"+
			"<td>"+oListItem.get_item('Title')+"</td>"+
			"<td>"+oListItem.get_item('ProjectName')+"</td>"+
			"<td>"+oListItem.get_item('ProjectNumber')+"</td></tr>";

			
			items.push([oListItem.get_item('ID'),oListItem.get_item('PriorityNumber')]);
		}
		
			htmlTbl += "</tbody></table>";
		
			$("#divListItems").html(htmlTbl);
			
			/*Apply DataTable style */
			var table = $('#prioritize').DataTable();
			
		$('table#prioritize').on('change','input[type=text]',function(e){
				
			//Value being replaced
			var curVal =  $(this).attr('data-curVal');
			
			//New Value
			var newVal = $(this).val();
		    		    
		   //Unique id of List Item. Format: 'rowID-xx' 
		   var itemID =  $(this).attr('id');
		   var id=getId(itemID);   
		   
		   /*Update and Prioritize*/
		   prioritize(newVal, id, curVal);
	    
		});		
	
	
	}
	
	/*Grab the id from the id name. Format: 'rowID-xx'*/
	function getId(iID) {
		var myID = iID.split("-");	
		var ID = myID[1];
		
		return ID;
	}

	function prioritize(uValue, uid, prevVal) {
	        update(uValue, uid);
	        
	  for (x = 0; x < items.length; x++) {
	    for (i = 0; i < 1; i++) {
	      if (items[x][0] === parseInt(uid)) {       	
	        if (uValue > prevVal) {
	       // alert(uValue+">"+prevVal);
	          for (j = parseInt(prevVal) - 1; j < uValue; j++) {
	            if (items[j][0] != uid)
	              items[j][1] = parseInt(items[j][1]) - 1;
	              alert(items[j][1]+"="+parseInt(items[j][1]) - 1);
	          }
	        } else {
	          for (j = parseInt(uValue ) - 1; j < parseInt(prevVal); j++) {
	            if (items[j][0] != uid)
	              items[j][1] = parseInt(items[j][1]) + 1;
	              alert(items[j][1]+"="+parseInt(items[j][1]) + 1);
	          }
	        }
	
	      }
	    }
	  }
	}

	/*Updates item with new priority value*/
	function update(pVal, itID){
		var rowID = parseInt(itID);
		var ptVal = parseInt(pVal);
		var ctx = new SP.ClientContext.get_current();
		var customList = ctx.get_web().get_lists().getByTitle('ParkFundingForm');
		var listItem = customList.getItemById(rowID);
		
		/*Set the value and update*/
		listItem.set_item('PriorityNumber', ptVal);
		listItem.update();
	 
		ctx.executeQueryAsync(
	    	function(){ 
			    		/*Need to change this to show on the page*/
			    		alert('Item updated'); 
			}, 
			
			function(sender, args){ alert('Error: ' + args.get_message()); });
			}
		
			function onQueryFailed(sender, args) {
				alert('Request failed. '+args.get_message() + '\n' + args.get_stackTrace());
	}
	
function getFieldNames(listName,viewName){

   var context = new SP.ClientContext.get_current();
   var web = context.get_web();
   var list = web.get_lists().getByTitle(listName);
   var view = list.get_views().getByTitle(viewName);
   var listFields = view.get_viewFields();
   context.load(listFields);
   context.executeQueryAsync(printFieldNames,onError);


   function printFieldNames() {
      var e = listFields.getEnumerator();
      while (e.moveNext()) {
         var fieldName = e.get_current();
         var buildColumns = "<th>"+fieldName+"</th>";
      }
   }

   function onError(sender,args)
   {
      console.log(args.get_message());
   }

}

Open in new window

0
Comment
Question by:Isaac
  • 2
3 Comments
 
LVL 31

Expert Comment

by:Jamie McAllister MVP
ID: 41847889
I think this might be going a bit wrong on line 57. You call GetFieldNames on line 54, fine, but then again on 57?

I think you should make your variable 'buildColumns' global and put that in the concat statement in line 57.
0
 
LVL 31

Accepted Solution

by:
Jamie McAllister MVP earned 500 total points
ID: 41848092
For further clarity; So I'm seeing the query being run async, fine. But in the eventual method to handle the result we call printFieldNames.

In there is this line in a while loop;

var buildColumns = "<th>"+fieldName+"</th>";

This is getting redeclared and overwritten each loop instead of the concat happening. I'm guessing this is where the concat is failing, if successful you could use this in Line 57.... except beware of timing issues as the method is called async. I think the work that line 57 does should be moved into the processing of teh async call later on to avoid issues...

All the above assuming I'm understanding your intent.
0
 
LVL 5

Author Closing Comment

by:Isaac
ID: 41849580
Thanks!
0

Featured Post

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Summary In SharePoint 2010 it is easy to create custom color themes to jazz up a site. Theme colors can also be created in PowerPoint 2010 with a few clicks. But how do the chosen colors actually look in the SharePoint site? The attached PowerPoint…
The vision: A MegaMenu for a SharePoint portal home page The mission: Make it easy to maintain. Allow rich content and sub headers as well as standard links. Factor in frequent changes without involving developers or a lengthy Dev/Test/Prod rel…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now