-->
Showing posts with label ECMA. Show all posts

SharePoint Custom file attachment control

Attach multiple files to SharePoint list item with custom upload control.
we can do the below features to your file upload control

1. Add Client Validation
2. Avoid duplicate file upload error
3. upload multiple attachments
4. include each document comments

Here we can use Custom Upload Control and OOB Attachments table.

HTML Code for Attachment Control:

                  

                
                        

                    
                


                
                     
 
                  


                  
                    
                  


                
              



Now we will include all feature step by Step

Step: 1
   
Client Validation for SharePoint file Upload Control

Step: 2
 Stop Showing duplicate file upload Error

Step: 3
 SharePoint add comments for each attached document



Get Current Loggedin User SharePoint Group Names using JQuery




To get the current user logged in SharePoint group name.
If you trying to iterate all the SharePoint groups the user may get access denied error.
Note: CSOM doesn't have impersonation facelity.

Here we can get only the specific group and find to get the logged user name


ExecuteOrDelayUntilScriptLoaded(IsCurrentUserHasContribPerms, 'SP.js');
function IsCurrentUserHasContribPerms() 
{
    IsCurrentUserMemberOfGroup("Members", function (isCurrentUserInGroup) 
    {
        if(isCurrentUserInGroup)
        {
            // The current user is in the [Members] group!
        }
    });
   

}

function IsCurrentUserMemberOfGroup(groupName, OnComplete) 
{

    var currentContext = new SP.ClientContext.get_current();
    var currentWeb = currentContext.get_web();

    var currentUser = currentContext.get_web().get_currentUser();
    currentContext.load(currentUser);

    var allGroups = currentWeb.get_siteGroups();
    currentContext.load(allGroups);

    var group = allGroups.getByName(groupName);
    currentContext.load(group);

    var groupUsers = group.get_users();
    currentContext.load(groupUsers);

    currentContext.executeQueryAsync(OnSuccess,OnFailure);

    function OnSuccess(sender, args) {
        var userInGroup = false;
        var groupUserEnumerator = groupUsers.getEnumerator();

        var OwnergroupUserEnumerator = OwnergroupUsers.getEnumerator();
   var statusval= $("select[title='ApprovalStatus'] option:selected").val();
        while (OwnergroupUserEnumerator.moveNext()) {
            var OwnergroupUser = OwnergroupUserEnumerator.get_current();
            if (OwnergroupUser.get_id() == currentUser.get_id()) {
                userInGroup = true;
               
                break;
            }
        }



        OnComplete(userInGroup);
    }

    function OnFailure(sender, args) {
        OnComplete(false);
    }    
}

Get and Set SharePoint 2013 People Picker Field using JQuery


Get and Set the Users or Names on SharePoint 2013 People Picker (Person Group) field on Custom List Forms using JQuery.

The SharePoint 2013 Client People Picker on Custom List forms is different from OOB control.
The "div" structure is different when compare with both. So we have to write different script on custom forms.

The below code will give an example to get and set the values for Client People Picker or Person Group Field on Custom List forms.


// Get People Picker Values
function getEditorPeoplePickerValues(fieldName) { // Field Title
        editorNames = "";
        var _PeoplePicker = $("div[title='" + fieldName + "']");
        var _PeoplePickerTopId = _PeoplePicker.attr('id');
        var ppobject = SPClientPeoplePicker.SPClientPeoplePickerDict[_PeoplePickerTopId];
        editorsInfo = ppobject.GetAllUserInfo();

        var i;
        for (i = 0; i < editorsInfo.length; ++i) {
            editorNames += editorsInfo[i].DisplayText + ";#";
        }
    }

// Set People Picker Values
function SetAndResolvePeoplePicker(fieldName, userAccountName) {
       // alert(userAccountName);
        var _PeoplePicker = $("div[title='" + fieldName + "']");
        var _PeoplePickerTopId = _PeoplePicker.attr('id');
        var _PeoplePickerEditer = $("input[title='" + fieldName + "']");

        userAccountName.split(";#").forEach(function (part) {
   if (part !== "" && part !== null) {
          //  alert(part);
            _PeoplePickerEditer.val(part);
            var _PeoplePickerOject = SPClientPeoplePicker.SPClientPeoplePickerDict[_PeoplePickerTopId];
            _PeoplePickerOject.AddUnresolvedUserFromEditor(true);
   }
        });

    }

// How to use the above function on our code

call direct function to get values. but to set values we have to create an array with names.
var editorNames = "";
getEditorPeoplePickerValues("Field Title");
SetAndResolvePeoplePicker("Field Title", editorNames );

SharePoint get deleted names from People Picker Field using jquery


Get deleted names or entries from SharePoint 2010 format People Picker control on list forms using JavaScript or JQuery.

Here we have to get values from the people picker at OnLoad and PreSaveAction and we have to get the values and set the values as below.


/*  */

var onloadViewerNames = [];
var presaveViewerNames = [];

jQuery(document).ready(function () {
 onloadViewerNames = getPickerInputElement("ff2"); // Get Viewer Names on load  
}); 

function PreSaveAction() {
 presaveViewerNames = getPickerInputElement("ff2"); // Get Viewer Names on pre save 
 var getDeletedViewer = $(onloadViewerNames).not(presaveViewerNames).get();
 var delvalues= "";
 if(getDeletedViewer.length){
  for (var i=0; i < getDeletedViewer.length; i++) {
   delvalues += getDeletedViewer[i] + "; ";
  }
  setPickerInputElement("ff6", delvalues)
 }
 
 return true;
}

// Get Users/Names from the Poeple Picker
function getPickerInputElement(identifier) {
 var tags = document.getElementsByTagName('DIV');
 var returnval = [];
 for (var i=0; i < tags.length; i++) {
  var tempString = tags[i].id;
  if ((tempString.indexOf(identifier) > 0) && (tempString.indexOf('UserField_upLevelDiv') > 0)){
   var innerSpans = tags[i].getElementsByTagName("SPAN");
   for(var j=0; j < innerSpans.length; j++) {
    if(innerSpans[j].id == 'content') {
     //return innerSpans[j].innerHTML;
     returnval.push(innerSpans[j].innerHTML);
    }
   }
  }
 }
 return returnval; 
}

// Set Deleted Users into another People Picker
function setPickerInputElement(identifier, value) {
  var tags = document.getElementsByTagName('DIV');

  for (var i=0; i < tags.length; i++) {
    var tempString = tags[i].id;
    //alert('tags[' + i + '].id = ' + tempString);
    if ((tempString.indexOf(identifier) > 0) && (tempString.indexOf('UserField_upLevelDiv') > 0)){
      //alert('HIT for ' + identifier + ' id=' + tags[i].id + ' value=' + tags[i].value);
      tags[i].innerHTML = value;
      break;
    }
  }
}

SharePoint Client Object Model using ECMAScript



To load the Java script Client Object Model, 
we have to call ExecuteOrDelayUntilScriptLoaded(Func, "sp.js") . This function takes the name of the function that need to be executed as a main function and will load the SP.js file, which is the core of Client Object Model. We have to load the current context in order to play with the site content by SP.ClientContext and then get the current site by calling get_web()function of current context. After getting the current site we call getByTitle to get the Product list and then we loaded that list. Note that we are not loading all the objects but only the list. Loading all the objects will cause delay and performance issues. We are loading the list asynchronously and if the call is successful OnSuccess()will be called and if the call failes OnFail() will be called.


Writing the ECMAScript

  1. Create a list called Product and add few items in it.
  2. Create a test ASPX page in the Pages library.
  3. Add the Content Editor web part and add the following script in it.

Creating a List Item Using ECMAScript (JavaScript, JScript)


var siteUrl = '/sites/MySiteCollection';

function createListItem() {

    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('Announcements');
        
    var itemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(itemCreateInfo);
        
    oListItem.set_item('Title', 'My New Item!');
    oListItem.set_item('Body', 'Hello World!');
        
    oListItem.update();

    clientContext.load(oListItem);
        
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {

    alert('Item created: ' + oListItem.get_id());
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Updating a List Item Using JavaScript

var siteUrl = '/sites/MySiteCollection';

function updateListItem() {

    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('Announcements');

    this.oListItem = oList.getItemById(3);

    oListItem.set_item('Title', 'My Updated Title');

    oListItem.update();

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {

    alert('Item updated!');
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Deleting a List Item Using JavaScript

var siteUrl = '/sites/MySiteCollection';

function deleteListItem() {

    this.itemId = 2;

    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('Announcements');

    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());
}

Example: 2

var siteUrl = '/sites/MySiteCollection';

function deleteListItemDisplayCount() {

    this.clientContext = new SP.ClientContext(siteUrl);
    this.oList = clientContext.get_web().get_lists().getByTitle('Announcements');

    clientContext.load(oList);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.deleteItem), Function.createDelegate(this, this.onQueryFailed));
}

function deleteItem() {

    this.itemId = 58;
    this.startCount = oList.get_itemCount();
    this.oListItem = oList.getItemById(itemId);

    oListItem.deleteObject();

    oList.update();

    clientContext.load(oList);
        
    clientContext.executeQueryAsync(Function.createDelegate(this, this.displayCount), Function.createDelegate(this, this.onQueryFailed));
}

function displayCount() {

    var endCount = oList.get_itemCount();
    var listItemInfo = 'Item deleted: ' + itemId + 
        '\nStart Count: ' +  startCount + ' End Count: ' + endCount;
        
    alert(listItemInfo)
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}