Friday, March 2, 2012

Article 1: Basic sharepoint 2010 EcmaScript Client Object Model (Load, Search, AddNew, Edit, Delete)


Demo User Interface

Step 1: Create List and name is ECMAScriptDemo Include Fields name is Title, User

Step 2: Open SPD and code below webpart of NewForm.aspx (Demo)
           Click Webpart NewItem | Scroll below and code after tag close </table> as follow
Step 3: Copy code below

<fieldset id="fldDemo1" style="width:300px">
        <legend>Demo 1 - fetching web title</legend>
        <div id="Div1" class="demoRow">
            <div class="demoControls">
                <button id="btnDemo1" type="button">
                    Fetch web title</button>
            </div>
        </div>
    </fieldset>
    <br/>
    <fieldset id="fldDemo2" style="width:300px">
        <legend>Demo 2 - fetching list items</legend>
        <div id="demo2Row" class="demoRow">
            <div class="demoControls">
                <button id="btnDemo2" type="button">
                    Fetch items</button>
            </div>
            <div class="demoResults">
                <span id="demo2Result" ></span>
            </div>
            <div class="clearer" />
        </div>
    </fieldset>
 <br/>
 <fieldset id="fldDemo3" style="width:300px">
        <legend>Demo 3 - fetching list items with query</legend>
        <div id="demo3Row" class="demoRow">
            <div class="demoControls">
                <label for="txtFilenameContains">
                    Filename contains:</label>
                <input type="text" id="txtFilenameContains" />
            </div>
            <div class="demoResults">
                <span id="demo3Result"> </span>
            </div>
            <div class="clearer" />
        </div>
     
    </fieldset>
   
    <br/>
    <fieldset id="fldDemo4" style="width:300px">
        <legend>Demo 4 - add list items</legend>
        <div id="demo4Row" class="demoRow">
            <div>
                <span class="demoLabel">ECMAScriptDemo title:</span><input id="txtTaskTitle" type="text" /></div>
            <div>
                <button id="btnAddTask" type="button">
                    Add ECMAScriptDemo</button></div>
            <div>
                <span class="demoLabel">Result:</span><span id="addResult" ></span></div>
        </div>
   
    </fieldset>
   
    <br/>
    <fieldset id="fldDemo5" style="width:300px">
        <legend>Demo 5 - edit list items</legend>
        <div id="demo5Row" class="demoRow">
            <div>
                <span class="demoLabel">ECMAScriptDemo title:</span><input id="txtECMAScriptDemoTitle" type="text" />
                <br/>
                <span class="demoLabel">ECMAScriptDemo id:</span><input id="txtECMAScriptDemoID" type="text" />
                </div>
            <div>
                <button id="btnEditECMAScriptDemo" type="button">
                    Edit ECMAScriptDemo</button></div>
            <div>
                <span class="demoLabel">Result:</span><span id="editResult" ></span></div>
        </div>
   
    </fieldset>
    <br/>
    <fieldset id="fldDemo6" style="width:300px">
        <legend>Demo 6 - delete list items</legend>
        <div id="demo6Row" class="demoRow">
            <div>
                <span class="demoLabel">ECMAScriptDemo id:</span><input id="txtECMAScriptDemoIDDelete" type="text" />
                </div>
            <div>
                <button id="btnDeleteECMAScriptDemo" type="button">
                    Delete ECMAScriptDemo</button></div>
            <div>
                <span class="demoLabel">Result:</span><span id="deleteResult" ></span></div>
        </div>
   
    </fieldset>

<script type="text/javascript" src="../../JqueryLibrary/jquery-1.4.2.js"></script>

//Get Title web 
<script type="text/javascript">
     var currentWeb;
     $('#btnDemo1').click(function () {
         //Get current Site
         var ctx = new SP.ClientContext.get_current();
         //Get current Web
         currentWeb = ctx.get_web();
         //Load Web
         ctx.load(currentWeb);
         //Call delegate
         ctx.executeQueryAsync(getWebSuccess, getWebFailure);
     });
     function getWebSuccess(sender, args) {
         alert('Title of current web is: ' + currentWeb.get_title());
     }
     function getWebFailure(sender, args) {
         alert('Failed to get web. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
     }   
 </script>
 //Get All
 <script type="text/javascript">
     var allDocs; $('#btnDemo2').click(function () {
         var ctx = new SP.ClientContext.get_current();
         var targetList = ctx.get_web().get_lists().getByTitle('Shared Documents');
         var query = SP.CamlQuery.createAllItemsQuery();
         allDocs = targetList.getItems(query); ctx.load(allDocs);
         ctx.executeQueryAsync(Function.createDelegate(this, getDocsAllItemsSuccess), Function.createDelegate(this, getDocsAllItemsFailure));
     });
     function getDocsAllItemsSuccess(sender, args) {
         var listEnumerator = allDocs.getEnumerator();
         while (listEnumerator.moveNext()) {
             $('#demo2Result').append(listEnumerator.get_current().get_item("FileLeafRef") + '<br />');
         }
     }
     function getDocsAllItemsFailure(sender, args) {
         alert('Failed to get list items. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
     }
 </script>
 // Search Item
  <script type="text/javascript">
      var selectedDocs;
      $('#txtFilenameContains').keyup(function (event) {
          filterDocs();
      });
      function filterDocs() {
          var ctx = new SP.ClientContext.get_current();
          var docLib = ctx.get_web().get_lists().getByTitle('Shared Documents');
          var query = new SP.CamlQuery();
          query.set_viewXml("<View><Query><Where><Contains><FieldRef Name='FileLeafRef'/><Value Type='Text'>" + $('#txtFilenameContains').val() + "</Value></Contains></Where></Query></View>");
          selectedDocs = docLib.getItems(query);
          ctx.load(selectedDocs);
          ctx.executeQueryAsync(getDocsWithQuerySuccess, getDocsWithQueryFailure);
      }
      function getDocsWithQuerySuccess(sender, args) {
          $('#demo3Result').empty();
          var listEnumerator = selectedDocs.getEnumerator();
          while (listEnumerator.moveNext()) {
              $('#demo3Result').append(listEnumerator.get_current().get_item("FileLeafRef") + '<br />');
          }
      }
      function getDocsWithQueryFailure(sender, args) {
          alert('Failed to get list items. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
      }
    </script>
         
          //Add New Item
          <script type="text/javascript">
              var newTask;
              $('#btnAddTask').click(function () {
                  var taskTitle = $('#txtTaskTitle').val();
                  //var taskDesc = $('#txtTaskDescription').val();
                  var ctx = new SP.ClientContext.get_current();
                  var taskList = ctx.get_web().get_lists().getByTitle('ECMAScriptDemo');
                  // use ListItemCreationInformation to provide values..       
                  var taskItemInfo = new SP.ListItemCreationInformation();
                  newTask = taskList.addItem(taskItemInfo);
                  newTask.set_item('Title', taskTitle);
                  newTask.set_item('User', 29);
                  // could set other fields here in same way..       
                  newTask.update();
                  ctx.load(newTask);
                  ctx.executeQueryAsync(addTaskSuccess, addTaskFailure);
                  function addTaskSuccess(sender, args) {
                      $('#addResult').html("ECMAScriptDemo " + newTask.get_item('Title') + " added to the ECMAScriptDemo list");
                  }
                  function addTaskFailure(sender, args) {
                      alert('Failed to add new ECMAScriptDemo. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
                  }
              });
          </script>
         
          //Edit Item
          <script type="text/javascript">
              var newTask;
              $('#btnEditECMAScriptDemo').click(function () {
                  updateListItem();
              });
              function updateListItem() {
                  var clientContext = new SP.ClientContext.get_current();
                  var oList = clientContext.get_web().get_lists().getByTitle('ECMAScriptDemo');
                  var title = $('#txtECMAScriptDemoTitle').val();
                  var id = $('#txtECMAScriptDemoID').val();
                  this.oListItem = oList.getItemById(parseInt(id));
                  oListItem.set_item('Title', title);
                  oListItem.update();
                  clientContext.executeQueryAsync(Function.createDelegate(this, this.UpdateQuerySucceeded), Function.createDelegate(this, this.UpdateQueryFailed));
              }
              function UpdateQuerySucceeded() {
                  alert('Item updated!');
              }
              function UpdateQueryFailed(sender, args) {
                  alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
              }         
   </script>
  
   //Delete Item
   <script type="text/javascript">
       var newTask;
       $('#btnDeleteECMAScriptDemo').click(function () {
           deleteListItem();
       });
       var itemId = '';
       function deleteListItem() {
           itemId = $('#txtECMAScriptDemoIDDelete').val();
           var clientContext = new SP.ClientContext.get_current();
           var oList = clientContext.get_web().get_lists().getByTitle('ECMAScriptDemo');
           this.oListItem = oList.getItemById(itemId);
           oListItem.deleteObject();
           clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
       }
       function onQuerySucceeded() {
           alert('Item deleted: ' + itemId);
       }
       function onQueryFailed(sender, args) {
           alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
       }
               
   </script>

Step 4: Run demo
  • Load Title web: when click button Fetch web title automatic popup and get Title of site is TeamSite.
              
  • Search Document: when typing character into textbox auto fill result
                        
  • Add new item
              When typing value into Textbox and click button Add....
                               
              Result:
                             
  • Edit item
                         
              Result:
                       
  • Delete item
              

              Result:
               
              

0 comments:

Post a Comment