Tuesday, 15 October 2019

SharePoint online - Get List-item attachments and Display to div

Step 1 : Create a List ex: TestList and attach few images

Step 2 : Copy and Pastet the below coding in App.js


var Items = null;
'use strict';
var listItems;
var hostweburl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
var appweburl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
$(document).ready(function () {
    SP.SOD.executeFunc('sp.js''SP.ClientContext', ListItems)
});

function ListItems() {
    var context = new SP.ClientContext(appweburl);
    var ContextSite = new SP.AppContextSite(context, hostweburl);
    var web = ContextSite.get_web();
    context.load(web);
    var list = web.get_lists().getByTitle('TestList');
    var caml = new SP.CamlQuery();
    caml.set_viewXml("<View><Query><FieldRef Name='Title' /></Query></View>"); // U can 

    Items = list.getItems(SP.CamlQuery.createAllItemsQuery());
    context.load(Items, 'Include(AttachmentFiles)'); 
    context.executeQueryAsync(onSucceededCallback, onFailedCallback);
}

function onSucceededCallback(sender, args) {
    var enumerator = Items.getEnumerator();
    var myText = '';
    for (var i = 0; i < Items.get_count() ; i++) {
        var item = Items.getItemAtIndex(i);

        //print attachments
        var attachments = item.get_attachmentFiles();
        for (var j = 0; j < attachments.get_count() ; j++) {
            var attachment = attachments.getItemAtIndex(j);
          
            var img = new Image(150, 150);
            img.src = attachment.get_serverRelativeUrl();
            myDiv.appendChild(img);

            myText += attachment.get_serverRelativeUrl();
            console.log(attachment.get_serverRelativeUrl());
        }
    }
  
    
}

function onFailedCallback(sender, args) {
    var myText = '<p>The request failed: <br>';
    myText += 'Message: ' + args.get_message() + '<br>';
    myDiv.innerHTML = myText;
}

function getQueryStringParameter(paramToRetrieve) {
    var params = document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve) return singleParam[1];
    }
}

Step 3: Copy and Paste the below coding in Default.aspx


<%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"MasterPageFile="~masterurl/default.master" Language="C#" %>

<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities"Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages"Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
    <SharePoint:ScriptLink name="sp.js" runat="server" OnDemand="true" LoadAfterUI="true"Localizable="false" />
    <meta name="WebPartPageExpansion" content="full" />

    <!-- Add your CSS styles to the following file -->
    <link rel="Stylesheet" type="text/css" href="../Content/App.css" />

    <!-- Add your JavaScript to the following file -->
    <script type="text/javascript" src="../Scripts/App.js"></script>
</asp:Content>

<%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
    Page Title
</asp:Content>

<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <div id="myDiv"></div>
    <div>
        <p id="message">
            <!-- The following content will be replaced with the user name when you run the app - see App.js -->         
        </p>
    </div>
</asp:Content>


Step 4: Appmainfest.xml

Give permission to Sitecollection - Full Control


Step 5: Deploy the Solution

Step 6:Final Result

Monday, 14 October 2019

SharePoint Online : Sharepoint Hosted App - People Picker Control using to insert and Show the Display Name in grid

Step 1:
Create a list in visual studio:



Step 2:
Create a fields like this




Step 3: Create one js file in the name of PeoplePicker.js
Step 4: Copy paste the below coding in PeoplePicker.js

PeoplePicker.js
--------------
var UserId;
var listname = "People";
var DisplayName;
$(document).ready(function () {
    initializePeoplePicker("UserName1");
    $('#btnSubmit').click(function (e) {
        PopulateGrid();
        if ($('#FilesGrid').html() == 'People') {
            addFile($('#UserName1').val());
            alert("UserNmae Adding to the Grid");
        }
        else {
            UpdateFiles($('#fileId').val());
        }
    });
});

function initializePeoplePicker(peoplePickerElementId) {
    var schema = {};
    schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
    schema['SearchPrincipalSource'] = 15;
    schema['ResolvePrincipalSource'] = 15;
    schema['AllowMultipleValues'] = false;
    schema['MaximumEntitySuggestions'] = 50;
    schema['Width'] = '250px';

    this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
}

function saveUser() {
    ensureUser();
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listname + "')/items",
        //_spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?$select=UserName1",
        type: "POST",
        async: false,
        data: JSON.stringify({
            __metadata: {
                type: "SP.Data.PeopleListItem"
            },
            UserName1Id: UserId,
            UserTitle: DisplayName

        }),

        headers: {
            "Accept": "application/json;odata=verbose",
            "Content-Type": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "X-HTTP-Method": "POST",
        },
        success: function (data) {

            alert("User Name is saved successfully:" + data);
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });
    //alert("Yes");
}

function ensureUser() {
    var peoplePickerTopDivId = $('#UserName1').children().children().attr('id');
    var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerTopDivId];
    var users = peoplePicker.GetAllUserInfo();

    var arryuser = users[0];

    if (arryuser) {
        var payload = { 'logonName': arryuser.Key };
        $.ajax({
            url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/ensureuser",
            type: "POST",
            async: false,
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(payload),
            headers: {
                "Accept": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val()
            },
            success: function (data, status, xhr) {
                UserId = data.d.Id;
           
                //DisplayName = data.d.results.DisplayText;
                DisplayName = data.d.Title;
           
             
            },
            error: function (xhr, status, error) {

            }
        });
    }
    else {
        UserId = 0;
    }
}

function PopulateGrid() {
    //Clear datatables
    $('#FilesGrid').empty();
    //Get File list items
    $.ajax({
        url: "../_api/web/lists/GetByTitle('" + listname + "')/items",
        method: "GET",
        headers: {
            "accept": "application/json;odata=verbose"
        },
        success: function (data) {
            if (data.d.results.length > 0) {
                //construct HTML Table from the JSON Data
                $('#FilesGrid').append(GenerateTableFromJson(data.d.results));
                //Bind the HTML data with Jquery DataTable
                var oTable = $('#PeopleTable').dataTable({

                    //control which datatable options available
                    dom: 'Bfrltip',
                    //add select functionality to datatable
                    select: true,
                    //adjust column widths
                    "columns": [
                        null,
                        null,

                        { "width": "8%" }
                    ],
                    //remove sort icon from actions column
                    "aoColumnDefs": [
                        { "bSortable": false, "aTargets": [2] }
                    ]
                });
            } else {
                $('#FilesGrid').append("<span>No People Found.</span>");
            }
        },
        error: function (data) {
            $('#FilesGrid').append("<span>Error Retreiving People. Error : " + JSON.stringify(data) + "</span>");
        }
    });
};


//Generate html table values
function GenerateTableFromJson(objArray) {
 
 
    var tableContent =
        '<table id="PeopleTable"  class="table table-striped table-bordered" cellspacing="0" width="100%">' +
        '<thead><tr>' + '<th>ID</th>' + '<th>UserName</th>' + '</tr></thead>';
    for (var i = 0; i < objArray.length; i++) {
        tableContent += '<tr>';
        tableContent += '<td>' + objArray[i].Id + '</td>';
        tableContent += '<td>' + objArray[i].UserTitle + '</td>';         
        tableContent += '</tr>';
    }
    '</table>';
    return tableContent;
};

//Edit file function
function UpdateFiles(id) {
    var UserName1 = $("#UserName1").val();
    var eTag = $("#etag").val();
    var requestUri = "../_api/web/lists/getByTitle('" + listname + "')/items(" + id + ")";
    var requestHeaders = {
        "accept": "application/json;odata=verbose",
        "X-HTTP-Method": "MERGE",
        "X-RequestDigest": $('#__REQUESTDIGEST').val(),
        "If-Match": eTag
    }
    var fileData = {
        __metadata: { "type": "SP.Data.PeopleListItem" },
        UserName1: UserName1

    };
    var requestBody = JSON.stringify(fileData);

    return $.ajax({
        url: requestUri,
        type: "POST",
        contentType: "application/json;odata=verbose",
        headers: requestHeaders,
        data: requestBody
    });
}
//Add File function
var addFile = function (Username1) {

    var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listname + "')/items",
        requestHeaders = {
            "accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": $('#__REQUESTDIGEST').val()
        }
    var fileData = {
        __metadata: { "type": "SP.Data.PeopleListItem" },
        UserName1: Username1

    };
    var requestBody = JSON.stringify(fileData);
    return $.ajax({
        url: requestUri,
        type: "POST",
        headers: requestHeaders,
        data: requestBody,

    });

};

Default.aspx
----------------
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <link type="text/css" href="../Content/App.css" rel="Stylesheet" />
    <link type="text/css" href="../Content/toastr.css" rel="stylesheet" />
    <link type="text/css" href="../Content/bootstrap.css" rel="stylesheet" />
    <link type="text/css" href="../Content/bootstrap-dialog.css" rel="stylesheet" />
    <link type="text/css" href="../Content/DataTables/css/select.bootstrap.min.css" rel="stylesheet" />
    <link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/1.10.8/css/jquery.dataTables.css" />
    <link type="text/css" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" />


</asp:Content>

<%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
    People Picker ...

</asp:Content>

<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script type="text/javascript" src="../_layouts/15/clienttemplates.js"></script>
        <script type="text/javascript" src="../_layouts/15/clientforms.js"></script>
        <script type="text/javascript" src="../_layouts/15/clientpeoplepicker.js"></script>
        <script type="text/javascript" src="../_layouts/15/autofill.js"></script>
     
        <script type="text/javascript" src="../Scripts/PeoplePicker.js"></script>
    </head>
    <body>
        <div id="FormLable">
            <div id="toolbar">
                <button type="button" value="Files" class="btn btn-info" onclick="Javascript: location.href = '../Lists/People'"><span class='glyphicon glyphicon-upload'></span>People List</button>
         
            </div>
            <div id="FilesPanel">
                <table class="table" style="width: 100%;">
                    <tr>
                        <td>
                            <div id="FilesGrid" style="width: 100%"></div>
                        </td>
                    </tr>
                </table>
            </div>

            <div id="peoplepickerlable">
                <label>User Name:</label>
                <div id="UserName1" class="peoplepicker">
                </div>
            </div>

            <div>
                <button type="button" id="btnSubmit" onclick="saveUser()" style="margin-top: 10px;">Submit</button>
            </div>
        </div>

    </body>
    </html>

</asp:Content>

Final result :


SharePoint online - Get List-item attachments and Display to div

Step 1 : Create a List ex: TestList and attach few images Step 2 : Copy and Pastet the below coding in App.js var  Items =  null ; ...