Search This Blog

Saturday, August 31, 2019

Using SPFX File uploaded in SharePoint document Library using Grid Data table









Using SPFX File uploaded in SharePoint document Library using Grid Data table
1-      Display Page


2- Add Page


2-   Edit Page

4-Delete Page

5- Library Name : column –Phone,FileDescription,Company

6- Create One Web part Name: Spfxseparatfile

1-SpfxseparatfileWebPart.module.scss
@import'~@microsoft/sp-office-ui-fabric-core/dist/sass/SPFabricCore.scss';

.spfxseparatfile {
.container {
max-width: 700px;
margin: 0pxauto;
box-shadow: 02px4px0rgba(0, 0, 0, 0.2), 025px50px0rgba(0, 0, 0, 0.1);
  }

.row {
@includems-Grid-row;
@includems-fontColor-white;
background-color: $ms-color-themeDark;
padding: 20px;
  }

.column {
@includems-Grid-col;
@include ms-lg10;
@include ms-xl8;
@include ms-xlPush2;
@include ms-lgPush1;
  }

.title {
@includems-font-xl;
@includems-fontColor-white;
  }

.subTitle {
@includems-font-l;
@includems-fontColor-white;
  }

.description {
@includems-font-l;
@includems-fontColor-white;
  }

.button {
// Our button
text-decoration: none;
height: 32px;

// Primary Button
min-width: 80px;
background-color: $ms-color-themePrimary;
border-color: $ms-color-themePrimary;
color: $ms-color-white;

// Basic Button
outline: transparent;
position: relative;
font-family: "Segoe UI WestEuropean","Segoe UI",-apple-system,BlinkMacSystemFont,Roboto,"Helvetica Neue",sans-serif;
-webkit-font-smoothing: antialiased;
font-size: $ms-font-size-m;
font-weight: $ms-font-weight-regular;
border-width: 0;
text-align: center;
cursor: pointer;
display: inline-block;
padding: 016px;

.label {
font-weight: $ms-font-weight-semibold;
font-size: $ms-font-size-m;
height: 32px;
line-height: 32px;
margin: 04px;
vertical-align: top;
display: inline-block;
    }
  }
}

2-SpfxseparatfileWebPart.ts

import { Version } from'@microsoft/sp-core-library';
import { BaseClientSideWebPart } from'@microsoft/sp-webpart-base';
import {
IPropertyPaneConfiguration,
PropertyPaneTextField
} from'@microsoft/sp-property-pane';
import { escape } from'@microsoft/sp-lodash-subset';

import { SPComponentLoader } from'@microsoft/sp-loader';
import styles from'./SpfxseparatfileWebPart.module.scss';
import*as strings from'SpfxseparatfileWebPartStrings';
import*as $ from'jquery';

import*astoastrfrom'toastr';
import { registerBeforeUnloadHandler } from'@microsoft/teams-js';

// Load JS and Css or external url in Page  if you want global declareation then used config file .

//1- Using Config
//1- its define in configJs after that used here
//require('tether');
//require('bootstrap');
//require('datatables.select');


//2- Its direct load From node_modules.
// require('../../../node_modules/bootstrap/dist/js/bootstrap.min.js');
require('../../../node_modules/datatables.net/js/jquery.dataTables.min.js');



//2- Usig By SPComponentLoader  Class
//  LaodCss File
SPComponentLoader.loadCss('https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/css/tether.min.css');
SPComponentLoader.loadCss('https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css');
SPComponentLoader.loadCss('https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css');
SPComponentLoader.loadCss('https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css');

// load Js File
SPComponentLoader.loadScript('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js');
//SPComponentLoader.loadScript('https://cdn.rawgit.com/rainabba/jquery-table2excel/1.1.0/dist/jquery.table2excel.min.js');
//SPComponentLoader.loadScript('https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/js/jquery.dataTables.min.js');


exportinterfaceISpfxseparatfileWebPartProps {
description: string;
}

exportdefaultclassSpfxseparatfileWebPartextendsBaseClientSideWebPart<ISpfxseparatfileWebPartProps> {

public render(): void {
this.domElement.innerHTML = `

<div class="container" style="overflow-x:auto;">

<h2><span class="label label-primary">Using SPFX File uploaded in sharepoint document Library Grid Datatable</span></h2><br>

<div id="toolbar">
<button type="button" value="Files" class="btnbtn-info" onclick="Javascript: location.href = 'https://mulltiverse.sharepoint.com/Lists/NGODoc'"><span class='glyphiconglyphicon-upload'></span> File List</button>
<button type="button" class="btnbtn-success addNewFile"><span class='glyphiconglyphicon-plus'></span> Add New File</button>
<button type="button" class="btnbtn-danger addexportToExcel"><span class='glyphiconglyphicon-plus'></span> Export to excel</button>
</div>
<p></p>

<div id="FilesPanel">
<table style="width: 80%">
<tr>
<td>
<div id="FilesGrid" style="width: 80% "></div>
</td>
</tr>
</table>
</div>

<!-- Bootstrap Modal Dialog for new/edit files-->
<div class="modal fade" id="myModalNorm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">&times;</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">
                    Add New File
</h4>
</div>
<!-- Modal Body -->
<div class="modal-body" id="modalBody">
<form role="form" id="fileForm">
<div class="form-group">
<label>File Title</label>
<input style="width:250px;" id="uploadFile" type="file" name="inputfile"/>
</div>
<div class="form-group">
<label>File Company</label>
<input class="form-control" id="fileCompany"/>
</div>
<div class="form-group">
<label>File Description</label>
<input class="form-control" id="fileDescription"/>
</div>
<div class="form-group">
<label>Phone</label>
<input class="form-control" id="filePhone"/>
</div>
<!-- hidden controls -->
<div style="display: none">
<input id="etag" />
<input id="fileId" />
</div>
</form>
<div class="modal-footer">
<button type="button" class="btnbtn-danger" data-dismiss="modal" onclick='updateFormLabel();'>
                        Cancel
</button>
<button type="submit" class="btnbtn-primary" id="fileFormSubmit">
                        Submit/Upload
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Bootstrap Modal Dialog for delete files-->
<div class="modal fade" id="deleteFiles" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">&times;</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel2">
                    Delete Confirmation
</h4>
</div>
<!-- Modal Body -->
<div class="modal-body" id="modalBody2">
<p>Are you sure you wish to delete this item?</p>
<form role="form" id="deleteForm">
<!-- hidden controls -->
<div style="display: none">
<input id="deleteId" />
</div>
</form>
<div class="modal-footer">
<button type="button" class="btnbtn-danger" data-dismiss="modal" '>
                        Cancel
</button>
<button type="submit" class="btnbtn-primary" id="deleteConfirmationSubmit">
                        Submit
</button>
</div>
</div>
</div>
</div>`; 

varabsuluteUrl=this.context.pageContext.web.absoluteUrl;

varRestUrl = absuluteUrl+ "/_api/lists/getbytitle('NGODoc')/items?$expand=Folder&$select=id,Title,Company,FileDescription,Phone,EncodedAbsUrl,FileRef,FSObjType,FileLeafRef,Folder/ServerRelativeUrl&$top=500";
        $(document).ready(function () {
PopulateGrid();
        $('#fileFormSubmit').click(function (e) {
debugger;

//Check for edit or new and call update or add function
if ($('#myModalLabel').html() == 'Add New File') {
addFile();
            } else {
UpdateFiles($('#fileId').val());
            }
        });

// delete Item from List
    $('#deleteConfirmationSubmit').click(function (e) {

debugger;
varrestUrl = absuluteUrl+ "/_api/web/lists/GetByTitle('NGODoc')/items(" + $('#deleteId').val() + ")";
varvdigest=getFormDigestValue();
      $.ajax({
url: restUrl,
type: "DELETE",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": vdigest,
"IF-MATCH": "*",
"Content-Type": "application/json;odata=verbose"
          },
success: function(data)  
          { 

          (<any>$('#deleteFiles')).modal('hide');
toastr.success("File Successfully Deleted.", "Success");
PopulateGrid();    
          }, 
error: function(data) 
          { 

toastr.error("File Successfully Error .", "Error Message")
//alert(data.responseJSON.error); 
          }
      });


    });


  });

functionPopulateGrid() {
//Clear datatables
    $('#FilesGrid').empty();
//Get File list items
    $.ajax({
url: RestUrl,
method: "GET",
headers: {
"accept": "application/json;odata=verbose"
        },
success: function (data) {
if (data.d.results.length>0) {
console.log(data.d.results);
//construct HTML Table from the JSON Data
                $('#FilesGrid').append(GenerateTableFromJson(data.d.results));
//Bind the HTML data with JqueryDataTable
varoTable = (<any>$('#FilesTable')).DataTable({
//control which datatable options available
dom: 'Bfrltip',
//add select functionality to datatable
select: true,
//adjust column widths
"columns": [
null,
null,
null,
null,
null,
                    { "width": "8%" }
],
//remove sort icon from actions column
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [5] }
                    ],
// start  Code for  Footer Fiter by Column value
initComplete: function () {
this.api().columns().every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
                                .appendTo( $(column.footer()).empty() )
                                .on('change', function () {
varval = $.fn.dataTable.util.escapeRegex(
                                        $(this).val()
                                    );
column
                                        .search(val ? '^'+val+'$' :'', true, false )
                                        .draw();
                                } );

column.data().unique().sort().each( function ( d, j ) {
select.append('<option value="'+d+'">'+d+'</option>' )
                            } );
                        } );
                    }
                });
// This code For Footer Going on Head Above section
                    

                $('#FilesTabletfoottr').insertBefore($('#FilesTabletheadtr'))
// This code For Footer Going on Head Above section
// start  Code for  Footer Fiter by Column value
            } else {
                $('#FilesGrid').append("<span>No Files Found.</span>");
            }
        },
error: function (data) {
            $('#FilesGrid').append("<span>Error Retreiving Files. Error : " + JSON.stringify(data) + "</span>");
        }
    });
};

//Generate html table values
functionGenerateTableFromJson(objArray) {
vartableContent =
'<table id="FilesTable" class="table table-striped table-bordered" cellspacing="0" ">' +
'<thead><tr>' +
'<th>ID</th>' +
'<th>File Name</th>' +
'<th>File Company</th>' +
'<th>File Description</th>' +
'<th>Phone</th>' +
'<th>Actions</th>' +
'</tr></thead>' +

'<tfoot><trvalign="top">' +
'<th>ID</th>' +
'<th>File Name</th>' +
'<th>File Company</th>' +
'<th>File Description</th>' +
'<th>Phone</th>' +
'</tr></tfoot>' ;



for (vari = 0; i<objArray.length; i++) {
tableContent += '<tr>';
tableContent += '<td>' + objArray[i].ID + '</td>';

tableContent += '<td><a  href=\''+objArray[i].FileRef +'\'  target="_blank">'+ objArray[i].FileLeafRef +'</a></td>';
// tableContent += '<td>' + objArray[i].FileLeafRef + '</td>';
tableContent += '<td>' + objArray[i].Company + '</td>';
tableContent += '<td>' + objArray[i].FileDescription + '</td>';
tableContent += '<td>' + objArray[i].Phone + '</td>';
tableContent += "<td><a id='" + objArray[i].ID + "' href='#' style='color: orange' class='confirmEditFileLink'>" +
"<i class='glyphiconglyphicon-pencil' title='Edit File'></i></a>&nbsp&nbsp";
tableContent += "<a id='" + objArray[i].ID + "' href='#' style='color: red' class='confirmDeleteFileLink'>" +
"<i class='glyphiconglyphicon-remove' title='Delete File'></i></a>&nbsp&nbsp";
tableContent += "<a id='" + objArray[i].ID + "' href='#' class='confirmListItemDetailsLink'>" +
"<i class='glyphiconglyphicon-cog' title='Link to List Item'></i></a></td>";
tableContent += '</tr>';
    }
returntableContent;
};
// Edit button click event
$(document).on('click', '.confirmEditFileLink', function (e) {
debugger;
e.preventDefault();
var id = this.id;
//alert(id);
varrequestUri = absuluteUrl+ "/_api/web/lists/getByTitle('NGODoc')/items(" + id + ")?$expand=File&$select=id,Title,Company,FileDescription,Phone,EncodedAbsUrl,FileRef,FSObjType,FileLeafRef,Folder/ServerRelativeUrl";
console.log(requestUri);
    $.ajax({
url: requestUri,
method: "GET",
contentType: "application/json;odata=verbose",
headers: {
"accept": "application/json;odata=verbose",
"content-Type": "application/json;odata=verbose"
      },
success: function (data) {
// $("#uploadFile").val(data.d.FileRef) ;
            $("#fileDescription").val(data.d.FileDescription) ;
            $("#fileCompany").val(data.d.Company) ;
            $("#filePhone").val(data.d.Phone) ;
            $('#fileId').val(id);
            $('#myModalLabel').html('Edit File');
            (<any>$('#myModalNorm')).modal('show');
            $("#etag").val(data.d.__metadata.etag);
        },
error: function(data) 
        { 
toastr.error("File Successfully Error .", "Error Message")
//alert(data.responseJSON.error); 
        }

    });
});
//Link to files list item
$(document).on('click', '.confirmListItemDetailsLink', function (e) {
e.preventDefault();
var id = this.id;
varrequestUri = absuluteUrl+ "/Lists/NGODoc/DispForm.aspx?ID=" + id;
window.location.href = requestUri;
});
// Delete button click event
$(document).on('click', '.confirmDeleteFileLink', function (e) {
e.preventDefault();
var id = this.id;
    $('#deleteId').val(id);
    (<any>$('#deleteFiles')).modal({
show: true
        })
});
//Update Model Label
functionupdateFormLabel() {
    $('#myModalLabel').html('Add New File');
};
//Populate then display modal dialog for add file button clicked
$(document).on('click', '.addNewFile', function (e) {
    $('#myModalLabel').html('Add New File');
    $("#uploadFile").val("") ;
    $("#fileDescription").val("") ;
    $("#fileCompany").val("") ;
    $("#filePhone").val("") ;
    (<any>$('#myModalNorm')).modal('show');
});

//Fuction for export to excel
$(document).on('click', '.addexportToExcel', function (e) {

});

// Update file function
functionUpdateFiles(id) {
debugger;
varFileDescription =$("#fileDescription").val() ;
var Company =$("#fileCompany").val() ;
var Phone =$("#filePhone").val() ;
vareTag = $("#etag").val();
varrequestUri = absuluteUrl + "/_api/web/lists/getByTitle('NGODoc')/items(" + id + ")";
varfileData = {
       __metadata: { "type": "SP.Data.NGODocItem" },
FileDescription: FileDescription,
       Phone: Phone,
       Company: Company
   };
varrequestBody = JSON.stringify(fileData);
varvdigest=getFormDigestValue();
return $.ajax({
url: requestUri,
type: "POST",
async:false,
headers:{
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": vdigest,
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE"
       }
       ,
data: requestBody,
success: function(data)  
       {
         (<any>$('#myModalNorm')).modal('hide');

PopulateGrid();    
toastr.success("File Successfully Update .", "Success") ;   
       }, 
error: function(data) 
       { 
        (<any>$('#myModalNorm')).modal('hide');
toastr.error("File Successfully Error  .", "Error Message") ;
//alert(data.responseJSON.error); 
       }

   });
}
//Add File function

functionaddFile() {
var files = (<HTMLInputElement>document.getElementById('uploadFile')).files;
//in case of multiple files,iterate or else upload the first file.
varvdigest=getFormDigestValue();
for (var x = 0; x <files.length; x++) {          
var file =files[x] ;
//var reader = new FileReader();
// reader.onloadend = function(evt)
// {
varcompleteUrl = absuluteUrl +"/_api/web/GetFolderByServerRelativeUrl('NGODoc')/Files/add(url='" + file.name + "',overwrite=true)?$select=*&$expand=ListItemAllFields";

        $.ajax({
url: completeUrl,
type: "POST",
data: file,
async: false,
processData: false,
headers: {
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": vdigest,
               },
complete: function (data) {
//alert(data.responseJSON.d.ListItemAllFields.Id);// Get Id from uploaded docs Id
// update meta Data or Other Column
                   $.ajax({
url: absuluteUrl +"/_api/Web/Lists/getByTitle('NGODoc')/Items("+data.responseJSON.d.ListItemAllFields.Id+")",
type: "POST",
data: JSON.stringify({
"__metadata": { type: "SP.Data.NGODocItem" },
FileDescription: $('#fileDescription').val(),
                       Company: $('#fileCompany').val(),
                       Phone:  $('#filePhone').val(),

                   }),
headers: {
                       Accept: "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": vdigest,
"IF-MATCH":"*",
"X-Http-Method": "MERGE"
                   },
success: function (data) {

                      (<any>$('#myModalNorm')).modal('hide');
PopulateGrid(); 
toastr.success("File Successfully Uploaded.", "Success");
                      $("#uploadFile").val("") ;
                      $("#fileDescription").val("") ;
                      $("#fileCompany").val("") ;
                      $("#filePhone").val("") ;

                     },
error: function (err) {
console.log(err);
                       }
               });
               },
error: function (err) {
// alert('failed');
               }
           });

//};
//reader.readAsArrayBuffer(file);
}  



};




functionPrintDocument(divName) {
varprintcontents = document.getElementById(divName).innerHTML;
varoriginablecontents = document.body.innerHTML;
document.body.innerHTML = printcontents;
window.print();
document.body.innerHTML = originablecontents;
 }
// Geting the formdigest value
functiongetFormDigestValue()
{
varvretrun="";
  $.ajax({
url: absuluteUrl + "/_api/contextinfo",
method: "POST",
async:false,
headers: {
"Accept": "application/json; odata=verbose",
"content-Type": "application/json;odata=verbose"

  },
success: function (data) {
debugger;
vretrun=data.d.GetContextWebInformation.FormDigestValue;
//console.log(vretrun);
returnvretrun;
    },
error: function (data, errorCode, errorMessage) {
toastr.error("File Successfully Error .", "Error Message")
alert(errorMessage)
    }

});
returnvretrun;
}

}  protectedgetdataVersion(): Version {
returnVersion.parse('1.0');
  }
protectedgetPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
        {
header: {
description: strings.PropertyPaneDescription
          },
groups: [
            {
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('description', {
label: strings.DescriptionFieldLabel
                })
              ]
            }
          ]
        }
      ]
    };
  }
}

3-Config.js
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"spfx-web-part": {
"components": [
        {
"entrypoint": "./lib/webparts/spfx/SpfxWebPart.js",
"manifest": "./src/webparts/spfx/SpfxWebPart.manifest.json"
        }
      ]
    },
"spfxseparatfile-web-part": {
"components": [
        {
"entrypoint": "./lib/webparts/spfxseparatfile/SpfxseparatfileWebPart.js",
"manifest": "./src/webparts/spfxseparatfile/SpfxseparatfileWebPart.manifest.json"
}
      ]
    },
"ngo-file-upload-web-part": {
"components": [
        {
"entrypoint": "./lib/webparts/ngoFileUpload/NgoFileUploadWebPart.js",
"manifest": "./src/webparts/ngoFileUpload/NgoFileUploadWebPart.manifest.json"
        }
      ]
    },
"image-gallery-web-part": {
"components": [
        {
"entrypoint": "./lib/webparts/imageGallery/ImageGalleryWebPart.js",
"manifest": "./src/webparts/imageGallery/ImageGalleryWebPart.manifest.json"
        }
      ]
    }
  },
"externals": {
"jquery": {
"path": "./node_modules/jquery/dist/jquery.min.js",
"globalName": "jQuery"
    },
"toastr": {
"path": "./node_modules/toastr/toastr.js",
"globalName": "jQuery"
    },
"tether": {
"path": "node_modules/tether/js/tether.js",
"globalName": "jQuery"
    },
"datatables.select": {
"path": "../../../node_modules/datatables.net/js/jquery.dataTables.min.js",
"globalName": "datatables.select",
"globalDependencies": [
"jquery"
      ]
    }
  },
"localizedResources": {
"SpfxseparatfileWebPartStrings": "lib/webparts/spfxseparatfile/loc/{locale}.js",
ss
  }
}