Loading...

Monday, December 5, 2011

Sharepoint Client Object Model:Working with Survey List and debugging ECMA Script

The List Schema for Survey List is quite different from the Custom Lists.
Every Question is added as the List column(Field)  and
Every Response to questions is added as   List Item.
To retrieve the Survey question and and To submit the response to List via Client Object Model,
do the following.


1)Load the reference of sp.js  and Load the address of function to be called as below
SP.SOD.executeOrDelayUntilScriptLoaded(DisplaySurveyQ,'SP.js');
2)Define the function.
var surveyItems = null;
var surveyFields=null;
var surveyList = null;
var oneField = null;

function DisplaySurveyQ()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
// of your desired target list:
surveyList = web.get_lists().getByTitle('surveylistName');
//alert(surveyList);
var caml = new SP.CamlQuery();
surveyItems = surveyList.getItems(caml);
surveyFields=surveyList.get_fields();
oneField = surveyFields.getByInternalNameOrTitle("Title"); 
//alert(surveyFields);
//alert(surveyItems);

//listOperations
context.load(oneField);
context.load(surveyList);
context.load(this.surveyItems);
context.load(this.surveyFields);  


context.load(list);
alert(list);

3) Create callback handlers in this function
var success = Function.createDelegate(this, this.onSuccess);
var failure = Function.createDelegate(this, this.onFailure);

4)Execute an async query in this function
context.executeQueryAsync(success,failure);
}

5)Define  Function On  success full operation.
// Async query succeeded.
function onSuccess(sender, args) {
// for example iterate through list items or fields and assign the value to  html controls like  div, uls etc
var listEnumerator = surveyItems.getEnumerator();
var listFieldEnumerator = surveyFields.getEnumerator();
var Fields=surveyList.get_fields();
var Questions=new Array();
var qCount=0;
//iterate though all of the Questions  and get the recently added question from Survey
var Count=0;
while (listFieldEnumerator .moveNext()) {
var currentField=listFieldEnumerator.get_current();
//alert(currentField.get_fieldTypeKind());
if(currentField.get_fieldTypeKind()==SP.FieldType.choice)
{
//alert(currentField.get_title());
Questions[qCount]=currentField;
}
Count= Count+ 1;
}
var currentField=Questions[qCount];
var FieldsChoices=currentField.get_choices() ;
 

// save the current questions internal name in hidden field , which will be helpful while submitting the response.
input type='hidden' name='CurrentQuestion' id='CurrentQuestion' value='"+currentField.get_internalName()

var divSurvey='generateRequiredHtml'
document.getElementById('generateRequiredHtmlandAssignThisIDmustPresent').innerHTML =divSurvey ;

}


6)Pass on the exception to UI by defining the failure function
// Async query failed.
function onFailure(sender, args)
{
alert(args.get_message());
}

7)To Submit Response to Survey List


function SubmitVote()
{
//Get the Group of radio Buttons for vote options  and get the selected value
//alert($("input[name='grpRadio']:checked").val());
if (undefined === $("input[name='grpRadio']:checked").val())
{
// do something
alert('Please select any response');
return;
}
// Get the current context
var context = new SP.ClientContext.get_current();
// Get the current site (SPWeb)
var web = context.get_web();
// Get the survey list
var list = web.get_lists().getByTitle('surveyListname');
 
var itemCreateInfo = new SP.ListItemCreationInformation();
var listItem = list.addItem(itemCreateInfo);
var response=document.getElementById('SelectedRadio').value;(response stored in hidden field)
var questionId=document.getElementById('CurrentQuestion').value (question's internal name stored in  hidden field)
/* Set fields in the item.
In managed code, this would be listItem[fieldname] = value.
In Javascript, call listItem.set_item(fieldName,value).
*/
listItem.set_item(questionId, response);
listItem.update();

 
// Create callback handlers
var success = Function.createDelegate(this, this.onSuccessVote);
var failure = Function.createDelegate(this, this.onFailureVote);
// Execute an async query
context.executeQueryAsync(success,failure);
}
// Async query succeeded.
function onSuccessVote(sender, args) {
alert('Thanks for responding Survey');
// Refresh the page.
// SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
}
// Async query failed.
function onFailureVote(sender, args) {
alert(args.get_message());
}


8)Add the above code lines  in txt file as follows

///less than sign![CDATA[   -- above code lines  here--

]]grater than  sign script ends

 //static html  here inside div div to assign generated html)
9)To debug above code place debugger; after any code line,which helps you to debug client object code with Visual Studio debugger.

10)Save this file as .txt file and upload to library and refer this link in content editor  webpart
This post is for good maintainability of code  on Sharepoint site itself .  That's gr8.. .  :)

Download Source Code