Odd: Can't add columns to a list

Feb 5, 2013 at 8:31 PM
So I'm trying to create a list then add a few fields to it. I've nabbed some code but it's not seeming to work. At the moment the list is created but the new column aint added despite it saying it is. Any thunks?
function createlist() {
 alert('wotcha');
 alert(filename);

 //Create list
 $().SPServices({
    operation: "AddList",
    listName: filename,
    description: "List created for quiz: "+filename,
    templateID: 100
 });
 
 //Add field: Score
    var nfields = "";
    nfields += "<Fields><Method ID='1'><Field Type='Text' DisplayName='DayCount' ResultType='Text'></Field></Method></Fields>";
    $().SPServices({
        operation: 'UpdateList',
        listName: filename,
        newFields: nfields,
        completefunc: function(xData, Status) {
            tp1 = xData.responseText;
            alert(tp1);
            tp4 = tp1.indexOf("errorstring");
            if (tp4 < 0) {
                alert("Fields created!");
            }
            else {
                // Error creating fields!
                alert("Error creating fields!");
            }
        }
    });

 alert('should be doned');
}
Feb 5, 2013 at 8:50 PM
Fiddling a little, and hard-coding the list name in:
 //Add field: Score

    var newFields = "<Fields>";
    for(i=1; i <= 100; i++) {
      newFields += "<Method ID='" + i + "'>" +
        "<Field Type='Text' DisplayName='Column_" + i + "' FromBaseType='TRUE' MaxLength='255' Description='Description of Column_" + i + "' />" +
        "</Method>";
    }
    newFields += "</Fields>";
    // Add a lot of columns to the list
    $().SPServices({
      operation: "UpdateList",
      listName: 'test1',
      newFields: newFields,
      completefunc: function (xData, Status) {
        alert(Status);
        alert(xData.responseText);
      }
    });
Gives me an error saying the list doesn't exist. Then the second time it looks like it works but doesn't create the column :'(
Coordinator
Feb 7, 2013 at 8:05 PM
Did you figure this out?

M.
Feb 7, 2013 at 9:19 PM
Hi Marc,

No I didn't. Im fiddling with another problem at the moment, but will have to come back to that one!
thanks

Oli
Coordinator
Feb 11, 2013 at 1:16 PM
Oli:

I just ran this code and it worked. Note that I have the AddList operation commented out because I wanted to run UpdateList several times to make sure that I could add columns repeatedly.
  $(document).ready(function() {

    //Create list
    /* $().SPServices({
        operation: "AddList",
        listName: "foo",
        description: "List created for quiz: foo",
        templateID: 100
    });
    */
    //Add field: Score
    var nfields = "<Fields><Method ID='1'><Field Type='Text' DisplayName='DayCount2' ResultType='Text'></Field></Method></Fields>";
    $().SPServices({
        operation: 'UpdateList',
        listName: "foo",
        newFields: nfields,
        completefunc: function(xData, Status) {
            tp1 = xData.responseText;
            alert(tp1);
            tp4 = tp1.indexOf("errorstring");
            if (tp4 < 0) {
                alert("Fields created!");
            }
            else {
                // Error creating fields!
                alert("Error creating fields!");
            }
        }
    });

});
Feb 11, 2013 at 2:09 PM
I think I must be losing it. I just ran your code three times. Once with the AddList bit active (created the list fine - failed on adding fields - presume the list wasn't ready) and the second two with it commented out. Both said fields created, but no fields were actually created. Image

garg!
Coordinator
Feb 11, 2013 at 2:11 PM
Edited Feb 11, 2013 at 2:12 PM
Take a look at the network traffic with Fiddler or Firebug to see what the response is when you try to create the columns. There ought to be some clue there.

M.

p.s. I ran my test on WSS 3.0 because I had it handy. Let me know if you'd like me to test with SharePoint 2010.
Feb 11, 2013 at 2:15 PM
I'm just trying to figure out how to use firebug :)

I'm using SP2010 I believe, if you get chance to try would be great
Coordinator
Feb 11, 2013 at 2:30 PM
Worked fine for me in 2010 as well.

M.
Feb 11, 2013 at 2:36 PM
Hang on a fruit cake...

When I look at the list in the UI, I'm getting what I showed you above. Even tryed the old Ctrl+F5 to clear the cache. So I've been going on the assumption that it aint worked.

BUT when I load up the list in SharePoint Designer I've got five counts of "DayCount2" listed where I've been running the script and it's been adding them... they're just not showing up for some reason!
Feb 11, 2013 at 2:38 PM
...and when I add an item, it's showing me the fields, but once its saved it's hiding them from that view and only shows if I click on the item again
Coordinator
Feb 11, 2013 at 2:44 PM
Adding the columns to the list won't add them to the default view. You'd need to do that separately.

M.
Feb 11, 2013 at 2:46 PM
live and learn.

I'll get to that in a bit - at least now I've got some more functionality I can ad :)
Feb 11, 2013 at 5:42 PM
Well, I think I'm there! I'm going to get this beta tested by a group of Year 9 students tomorrow, but I'll put the code below for reference to anyone that might find it interesting. I'm sure I've made loads of faux-par's as I've written a grand total of about three things in JavaScript, and have very limited knowledge of SP. But first, some context:

I am a teacher - running the ICT and Computer Science department of a South London Academy - we teach both disciplines to 11-18year olds. For key-stage 3 (Y7, 8 and 9) we have for the last few years set homework on our VLE (Virtual Learning Environment) which had a built-in testing system. Due to that being about the only part of the VLE that wasn't naff, it was recently retired and a new SharePoint system brought in. It's got a few bespoke bits, and I am not an admin. Now I'm faced with the dilema: I have 555-ish students needing their homework setting every week, I deliver all my learning resources via the SP system, but there is no built-in quizzing system. Yes - there are surveys, but they don't mark and have their own foibles. So I built this JS based quizzing system.

Methodology: The teacher in charge of setting homework that week creates a multiple-choice quiz on a stand-alone piece of client software I wrote in Delphi. This then creates an array string which it pastes into the quiz template (with a relevant name) and copies (I hope - haven't tested that bit as not on the local network!) the file to the relevant document store in the SP server. The teacher then just creats a link from the homework page to the relevant quiz, and when the kids hit the quiz the results go into the relevant list (created with the same name as the quiz). The difficult bit was making sure that the list was created the first time the quiz is run. The idea is the teacher hits the quiz once the link is up to make sure it's worked. When they submit it creates the list, adds the columns, and updates the view. The second time it tests if the list exists (it does now!) and just inserts their score, which it also shows to the kids and then closes the window.

Wheeee :)
<!doctype html>

<html lang="en">
<head>
 <meta charset="utf-8" />
 <title>jQuery UI Tabs - Default functionality</title>
 <link rel="stylesheet" href="/mertonshared/computerstudies/homework/Documents/includes/jquery-ui.css" />
 <script language="javascript" src="/mertonshared/computerstudies/homework/Documents/includes/jquery-1.8.1.js"></script>
 <script language="javascript" src="/mertonshared/computerstudies/homework/Documents/includes/jquery-ui.js"></script>
 <script language="javascript" src="/mertonshared/computerstudies/homework/Documents/includes/jquery.SPServices-0.7.2.js" type="text/javascript"></script>
 <script>
 //////////////////////////////////////////////////////////
 // Quizzer v1.0.2                                       //
 // Change Log:                                          //
 //  - 1.0.2 Removed some pointless alerts for ordinary  //
 //           users, reenabled windows.close(), added    //
 //           some useful comments.                      //
 //  - 1.0.1 Added view change to show all fields        //
 // Currently available:                                 //
 //  - Multiple choice                                   //
 //  - Unlimited questions                               //
 //  - Four options per question                         //
 // Future Plans                                         //
 //  - Varying number of options per question            //
 //  - Missing word completion                           //
 //  - Include YouTube clip                              //
 //////////////////////////////////////////////////////////
 
 var startseconds;
 var filename;
 var score;
 
 function checkiflistexists() {
    //alert('checking existance of list: '+filename);
    $().SPServices ({
        operation: "GetList",
        listName:  filename,
        completefunc: function (xData, Status) {
                //tp1 = xData.responseText;
                //alert(tp1);
                //alert(Status);
                if (Status == 'success') {
                    //alert ('Exists - dont create - just insert data');
                    insertdata();
                }
                else {
                    alert('Dont exist');
                    $().SPServices({
                        operation: "AddList",
                        listName: filename,
                        description: "List created for quiz: "+filename,
                        templateID: 100,
                        completefunc: function (xData, Status) {
                            alert('Trying to create list');
                            alert(Status);
                            alert('Now add fields');
                            var nfields = "<Fields><Method ID='1'><Field Type='Text' DisplayName='Score' ResultType='Text'></Field></Method><Method ID='2'><Field Type='Text' DisplayName='TimeTaken' ResultsType='Text'></Field></Method><Method ID='3'><Field Type='Text' DisplayName='CompletedOn' ResultsType='Text'></Field></Method></Fields>";
                            $().SPServices({
                                operation: 'UpdateList',
                                listName: filename,
                                newFields: nfields,
                                completefunc: function(xData, Status) {
                                    tp1 = xData.responseText;
                                    tp4 = tp1.indexOf("errorstring");
                                    if (tp4 < 0) {
                                        alert("Fields created! - Update View");
                                        var viewname = "";
                                        $().SPServices({
                                            operation: "GetViewCollection",
                                            async: false,
                                            listName: filename, 
                                            completefunc: function (xData, Status) {
                                                alert('Complete Func - GewViewCollection');
                                                $(xData.responseXML).find("[nodeName='View']").each(function() {
                                                    var viewdisplayname = $(this).attr("DisplayName");
                                                    if (viewdisplayname=="AllItems") {
                                                        viewname = $(this).attr("Name");
                                                        return false;
                                                    }
                                                });
                                            } 
                                        }); 
                                        alert('Ok - done GetViewCollection - now update the view');
                                        var viewfields = "<ViewFields><FieldRef Name=\"Title\" /><FieldRef Name=\"Score\" /><FieldRef Name=\"TimeTaken\" /><FieldRef Name=\"CompletedOn\" /></ViewFields>";
                                        $().SPServices({
                                            operation: 'UpdateView',
                                            async: false,
                                            listName: filename,
                                            viewName: viewname,
                                            viewFields: viewfields,
                                            completefunc: function(xData, Status) {
                                                alert('Trying to update view');
                                                alert(Status);
                                                alert('Updated view - now add data!');
                                                insertdata();
                                            }
                                        });
                                    }
                                    else {
                                    // Error creating fields!
                                    alert("Error creating fields!");
                                    }
                                }
                            });
                        }
                    });
                }
            }
        });
 }

 function insertdata() {
    var thisUserName = $().SPServices.SPGetCurrentUser({
        fieldName: "Title",
        debug: false
    });
    var endseconds = new Date().getTime() / 1000;
    endseconds = endseconds - startseconds;
    var d = new Date(); 
    var dd = d.toDateString(); 
    var dt = d.toTimeString(); 
    $().SPServices({
        operation: "UpdateListItems",
        async: false,
        batchCmd: "New",
        listName: filename, 
        valuepairs: [["Title", thisUserName],["Score",score],["TimeTaken",Math.round(endseconds).toString()+" seconds"],["CompletedOn",dd+" "+dt]],
        completefunc: function (xData, Status) {
            //alert('Trying to add data');
            if (Status == 'success') {
                inserted();
            }
            else {
                alert(Status+' : There was a problem inserting your score into the database. Please notify Mr Howson!');
                inserted();
            }
        }
    });
    alert('You achieved a score of '+score);
 }
 
 function checkanswers() {
    var form = document.getElementById('answers');
    score = 0;
    for (var i = 0; i < form.elements.length; i++ ) {
        if (form.elements[i].type == 'radio') {
            if (form.elements[i].checked == true) {
                if (questions[form.elements[i].name.substring(9)-1][questions[form.elements[i].name.substring(9)-1].length-1] == form.elements[i].value)
                {
                 score++;
                }
            }
        }
    }
  var url = window.location.pathname;
  filename = url.substring(url.lastIndexOf('/')+1);
  filename = filename.substring(0,filename.lastIndexOf('.'));
  $(document).ready(function() {  
    checkiflistexists();
  }); 
 }
 
 function starttime() {
    startseconds = new Date().getTime() / 1000;
 }
 
 function inserted() {
    window.close();
 }
  
 $(function() {
  $( "#tabs" ).tabs();
 });
 
 var questions = new Array;
  //The section below should be uncommented when not testing - this will be replaced by the client
  // side application with the questions array.
//[INSERTQUESTIONS]

 //The following questions can be uncommented for testing purposes
 questions[0] = ['q1','a','b','c',1];
 questions[1] = ['q2','d','e','f',2];
 questions[2] = ['q3','g','h','i',3];
 </script>
</head>

<body onload="starttime()">
 <div id="tabs">
  <ul>
   <script language="JavaScript">
    for (var i = 0; i< questions.length; i++)
    {
     document.write('<li><a href="#tabs-'+(i+1)+'">Question '+(i+1)+'</a></li>');
    }
    document.write('<li><a href="#tabs-'+(i+1)+'">Summary</a></li>');
   </script>
  </ul>
   <form name="answers" id="answers">
   <script language="JavaScript">
    for (var i = 0; i < questions.length; i++)
    {
     document.write('<div id="tabs-'+(i+1)+'">');
     document.write(' <p>'+questions[i][0]+'</p>');
     for (var j = 1; j < questions[i].length-1; j++)
     {
      document.write(' <p><input type="radio" name="question-'+(i+1)+'" value="'+j+'">'+questions[i][j]+'<br></p>');
     }
     document.write('</div>');
    }
    document.write('<div id="tabs-'+(i+1)+'">');
    document.write(' <p><input type="submit" onclick="checkanswers(); return false;"></p>');
    document.write('</div>');
  </script>
  </form>
 </div>
</body>
</html>
Coordinator
Feb 11, 2013 at 5:51 PM
Oli:

I'd love to put this up as an SPServices Story. Are you game?

M.
Feb 11, 2013 at 5:53 PM
Of course - happy to share
Coordinator
Feb 11, 2013 at 5:56 PM
Great! I'll get it posted. As you progress along (assuming you may enhance this as you go) we can always do follow up posts.

M.
Feb 14, 2013 at 10:39 AM
I've updated - see the changelog for info :)
<!doctype html>

<html lang="en">
<head>
 <meta charset="utf-8" />
 <title>jQuery UI Tabs - Default functionality</title>
 <link rel="stylesheet" href="/mertonshared/computerstudies/homework/Documents/includes/jquery-ui.css" />
 <script language="javascript" src="/mertonshared/computerstudies/homework/Documents/includes/jquery-1.8.1.js"></script>
 <script language="javascript" src="/mertonshared/computerstudies/homework/Documents/includes/jquery-ui.js"></script>
 <script language="javascript" src="/mertonshared/computerstudies/homework/Documents/includes/jquery.SPServices-0.7.2.js" type="text/javascript"></script>
 <script>
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 // Quizzer v1.0.2                                                                                //
 // Change Log:                                                                                   //
 //  - 1.1.0 Added check whether user has completed before - one try only. Reordered some actions //
 //          Added permissions setting when list is being created. Changed submit button value.   //
 //  - 1.0.2 Removed some pointless alerts for ordinary users, reenabled windows.close(), added   //
 //           some useful comments.                                                               //
 //  - 1.0.1 Added view change to show all fields                                                 //
 // Currently available:                                                                          //
 //  - Multiple choice                                                                            //
 //  - Unlimited questions                                                                        //
 //  - Four options per question                                                                  //
 // Future Plans                                                                                  //
 //  - Varying number of options per question                                                     //
 //  - Missing word completion                                                                    //
 //  - Include YouTube clip                                                                       //
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 var startseconds;
 var filename;
 var score;
 var thisUserName;
 var previouslytried;
 
 function checkiflistexists() {
    //alert('checking existance of list: '+filename);
    $().SPServices ({
        operation: "GetList",
        listName:  filename,
        completefunc: function (xData, Status) {
                //tp1 = xData.responseText;
                //alert(tp1);
                //alert(Status);
                if (Status == 'success') {
                    //alert ('Exists - dont create - just insert data');
                    insertdata();
                }
                else {
                    alert('Dont exist');
                    $().SPServices({
                        operation: "AddList",
                        listName: filename,
                        description: "List created for quiz: "+filename,
                        templateID: 100,
                        completefunc: function (xData, Status) {
                            alert('Trying to create list');
                            alert(Status);
                            alert('Now add fields');
                            var nfields = "<Fields><Method ID='1'><Field Type='Text' DisplayName='Score' ResultType='Text'></Field></Method><Method ID='2'><Field Type='Text' DisplayName='TimeTaken' ResultsType='Text'></Field></Method><Method ID='3'><Field Type='Text' DisplayName='CompletedOn' ResultsType='Text'></Field></Method></Fields>";
                            $().SPServices({
                                operation: 'UpdateList',
                                listName: filename,
                                newFields: nfields,
                                completefunc: function(xData, Status) {
                                    tp1 = xData.responseText;
                                    tp4 = tp1.indexOf("errorstring");
                                    if (tp4 < 0) {
                                        alert("Fields created! - Update View");
                                        var viewname = "";
                                        $().SPServices({
                                            operation: "GetViewCollection",
                                            async: false,
                                            listName: filename, 
                                            completefunc: function (xData, Status) {
                                                alert('Complete Func - GewViewCollection');
                                                $(xData.responseXML).find("[nodeName='View']").each(function() {
                                                    var viewdisplayname = $(this).attr("DisplayName");
                                                    if (viewdisplayname=="AllItems") {
                                                        viewname = $(this).attr("Name");
                                                        return false;
                                                    }
                                                });
                                            } 
                                        }); 
                                        alert('Ok - done GetViewCollection - now update the view');
                                        var viewfields = "<ViewFields><FieldRef Name=\"Title\" /><FieldRef Name=\"Score\" /><FieldRef Name=\"TimeTaken\" /><FieldRef Name=\"CompletedOn\" /></ViewFields>";
                                        $().SPServices({
                                            operation: 'UpdateView',
                                            async: false,
                                            listName: filename,
                                            viewName: viewname,
                                            viewFields: viewfields,
                                            completefunc: function(xData, Status) {
                                                alert('Trying to update view');
                                                alert(Status);
                                                alert('Updated view - now update permissions');
                                                //insertdata();
                                                $().SPServices({
                                                    operation: 'AddPermission',
                                                    objectType: 'List',
                                                    objectName: filename,
                                                    permissionIdentifier: "HARRISNET\\ham-grp-students",
                                                    permissionType: 'user',
                                                    permissionMask: 1011028719,
                                                    completefunc: function(xData, Status) {
                                                        alert('Trying to update permissions');
                                                        alert(Status);
                                                        alert(xData.responseXML.xml);
                                                        alert('Done... hopefully! - better insert the data!');
                                                        insertdata();
                                                    }
                                                });
                                            }
                                        });
                                    }
                                    else {
                                    // Error creating fields!
                                    alert("Error creating fields!");
                                    }
                                }
                            });
                        }
                    });
                }
            }
        });
 }

 function insertdata() {
    var endseconds = new Date().getTime() / 1000;
    endseconds = endseconds - startseconds;
    var d = new Date(); 
    var dd = d.toDateString(); 
    var dt = d.toTimeString(); 
    $().SPServices({
        operation: "UpdateListItems",
        async: false,
        batchCmd: "New",
        listName: filename, 
        valuepairs: [["Title", thisUserName],["Score",score],["TimeTaken",Math.round(endseconds).toString()+" seconds"],["CompletedOn",dd+" "+dt]],
        completefunc: function (xData, Status) {
            //alert('Trying to add data');
            if (Status == 'success') {
                //inserted();
            }
            else {
                alert(Status+' : There was a problem inserting your score into the database. Please notify Mr Howson!');
                //inserted();
            }
        }
    });
    alert('You achieved a score of '+score);
    window.close();
 }
 
 function checkanswers() {
    var form = document.getElementById('answers');
    score = 0;
    for (var i = 0; i < form.elements.length; i++ ) {
        if (form.elements[i].type == 'radio') {
            if (form.elements[i].checked == true) {
                if (questions[form.elements[i].name.substring(9)-1][questions[form.elements[i].name.substring(9)-1].length-1] == form.elements[i].value)
                {
                 score++;
                }
            }
        }
    }
  $(document).ready(function() {  
    checkiflistexists();
  }); 
 }
 
 function initialise() {
    var rowcount = 0;
    startseconds = new Date().getTime() / 1000;
    var url = window.location.pathname;
    thisUserName = $().SPServices.SPGetCurrentUser({
        fieldName: "Title",
        debug: false
    });
    filename = url.substring(url.lastIndexOf('/')+1);
    filename = filename.substring(0,filename.lastIndexOf('.'));
    //alert(filename);
    //alert('Getting items');
  $().SPServices({
    operation: "GetListItems",
    async: false,
    listName: filename,
    CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='Score' /></ViewFields>",
    CAMLQuery: "<Query><Where><Eq><FieldRef Name='Title' /><Value Type='Text'>"+thisUserName+"</Value></Eq></Where></Query>",
    CAMLRowLimit: 1,
    completefunc: function (xData, Status) {
      $(xData.responseXML).SPFilterNode("z:row").each(function() {
        //var liHtml = "<li>" + $(this).attr("ows_Title") + "</li>";
        score = $(this).attr("ows_Score");
        //$("#tasksUL").append(liHtml);
        rowcount++;
      });
    }
  });
    //alert(rowcount);
    //alert('done');
  if (rowcount > 0) {
   previouslytried = true;
   document.getElementById('tabs').style.visibility = 'hidden'; 
   alert('Sorry - you have already tried this quiz - one try only!\nLast time you got a '+score);
   window.close();
  }
  else {
   previouslytried = false;
  }
 }
 
 function inserted() {
    //window.close();
 }
  
 $(function() {
  $( "#tabs" ).tabs();
 });
 
 var questions = new Array;
  //The section below should be uncommented when not testing - this will be replaced by the client
  // side application with the questions array.
  [INSERTQUESTIONS]


 //The following questions can be uncommented for testing purposes
 //questions[0] = ['q1','a','b','c',1];
 //questions[1] = ['q2','d','e','f',2];
 //questions[2] = ['q3','g','h','i',3];
 </script>
</head>

<body onload="initialise()">
 <div id="tabs">
  <ul>
   <script language="JavaScript">
    for (var i = 0; i< questions.length; i++)
    {
     document.write('<li><a href="#tabs-'+(i+1)+'">Question '+(i+1)+'</a></li>');
    }
    document.write('<li><a href="#tabs-'+(i+1)+'">Summary</a></li>');
   </script>
  </ul>
   <form name="answers" id="answers">
   <script language="JavaScript">
    for (var i = 0; i < questions.length; i++)
    {
     document.write('<div id="tabs-'+(i+1)+'">');
     document.write(' <p>'+questions[i][0]+'</p>');
     for (var j = 1; j < questions[i].length-1; j++)
     {
      document.write(' <p><input type="radio" name="question-'+(i+1)+'" value="'+j+'">'+questions[i][j]+'<br></p>');
     }
     document.write('</div>');
    }
    document.write('<div id="tabs-'+(i+1)+'">');
    document.write(' <p><input type="submit" onclick="checkanswers(); return false;" value="Submit Homework"></p>');
    document.write('</div>');
  </script>
  </form>
 </div>
</body>
</html>