Search This Blog

Monday, April 29, 2019

Crud Operation On SharePoint List Using SPFX No Framework WebPart





Creating SPFX web part

The first step is to set up your dev environment for SharePoint framework development. if you have not already done so, follow this link to prepare environment Set up your SharePoint Framework development environment.
Now that you have finished setting up your environment, follow the steps below to create anspfx web part:
1. Open command line, cmd
2. Create a folder using the command md, call it spfx (i.e. md NoFrameworkCrudWebPart)
3. Navigate to the folder you just created using "cd NoFrameworkCrudWebPart" and type yo @microsoft/sharepoint 



4. Follow the screenshot below to create a solution for your web part. Note that you can name your web part AzureWebAPIWebPart as shown below or anything you wish. Just ensure that when you are copying the code from here, you replace your web part name where necessary.  



5. If all is well, you will seen a congratulations screen that looks like below. If there is any issue, ensure you fix it before going on to the next step.


6. You can run gulp serve to ensure everything is okay. This should launch your default browser. Click the plus sign and add your web part. If all is fine, you should see your web part with default look.
 Now let's install jquery and Typings for jquery as we require jqueryajax to make calls to our web API.
7. To add jquery to your project, on command line type:
     npmjquery --save
     npm @types/jquery --save
8. Then type "code ." without the quote to open visual studio code editor.
9. Click the drop down arrow next to src>Webparts>YourWebpartName 
10. Verify that jquery library was added successfully to your project by clicking the arrow next to nodes_modules>jquery> dist. Verify jquery.min.js is there.
Let's un-bundle the jquery library by externalizing it. This step is optional but good for page load performance.
11. Open Config.jsonYourWebpartName>Config>Config.json
12. Modify it as shown below

"externals": {
    "jquery": {
      "path": "node_modules/jquery/dist/jquery.min.js",
      "globalName": "jQuery"
    }
13. Go back to src and open YourWebpartName.ts. Let's import the jquery and load css file from a SharePoint library in the YourWebpartName.ts.



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

import { SPHttpClient, SPHttpClientResponse } from'@microsoft/sp-http'; 
import { IListItem } from'./IListItem'; 
import { SPComponentLoader } from'@microsoft/sp-loader';
import styles from'./NoFrameworkCrudWebPart.module.scss'; 
import*as strings from'NoFrameworkCrudWebPartStrings'; 
SPComponentLoader.loadCss('https://omniee.sharepoint.com/sites/NGO/SiteAssets/styles.css');

exportinterfaceINoFrameworkCrudWebPartProps { 
listName: string; 
} 
/*<div class="ms-Grid-row ms-bgColor-themeDarkms-fontColor-white ${styles.row}">

</div>

<div class="ms-Grid-row ms-bgColor-themeDarkms-fontColor-white ${styles.row}">
<div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
<div class="status"></div>
<ul class="items"><ul>
</div>
</div><p class="${ styles.subTitle }">No Framework</p>
<p class="${ styles.description }">Name: ${this.Listname}</p>  */
exportdefaultclassNoFrameworkCrudWebPartextendsBaseClientSideWebPart<INoFrameworkCrudWebPartProps> { 
privatelistItemEntityTypeName: string = undefined; 
privateListname :string="Students";
/* <button  style="display: none" class="${styles.button} read-Button">
<span  class="${styles.label}">Read item</span>
</button>

<button style="display: none" class="${styles.button} delete-Button">
<span class="${styles.label}">Delete item</span>
</button> */
public render(): void { 
this.domElement.innerHTML = ` 
<div class="${styles.noFrameworkCrud}">
<div class="${styles.container}">
<div class="${styles.row}">
<div class="${styles.column}">
<span class="${styles.title}"></span>

<div class="row">
<h2 style="text-align:left" id="statusMode">
              CRUD Operation From SharePoint List Using NoFramework SPFX Online 
</h4>
<div class="row">
<div class="col-25">
<label for="fname">Title</label>
</div>
<div class="col-75">
<input type="text" id="idTitle" name="Title" placeholder="Title.">
</div>
</div>
<div class="row">
<div class="col-25">
<label for="fname">Name</label>
</div>
<div class="col-75">
<input type="text" id="idfname" name="firstname" placeholder="Name.">
</div>
</div>
<div class="row">
<div class="col-25">
<label for="lname">Gender</label>
</div>
<div class="col-75">
<input type="text" id="idgender" name="gender" placeholder="Gender..">
</div>
</div>
<div class="row">
<div class="col-25">
<label for="country">Department</label>
</div>
<div class="col-75">
<input type="text" id="idDepart" name="lname" placeholder="Department..">
</div>
</div>
<div class="row">
<div class="col-25">
<label for="subject">City</label>
</div>
<div class="col-75">
<input type="text" id="idCity" name="gender" placeholder="City..">
</div>
</div>
<!-- hidden controls -->
<div style="display: none">
<input id="recordId" />
</div>
<div class="row">
<div class="ms-Grid-row ms-bgColor-themeDarkms-fontColor-white ${styles.row}">

<div  style="margin-left: 66px" class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1" >
<button class="${styles.button} create-Button">
<span class="${styles.label}">Save</span>
</button>
<button class="${styles.button} update-Button">
<span class="${styles.label}">Update</span>
</button>
<button  class="${styles.button} read-Button">
<span  class="${styles.label}">Clear All</span>
</button>
</div>
</div>
</div>
<div class="divTableblueTable">
<div class="divTableHeading">
<div class="divTableRow">
<div class="divTableHead">Title</div>
<div class="divTableHead">Name</div>
<div class="divTableHead">Gender</div>
<div class="divTableHead">Department</div>
<div class="divTableHead">City</div>
</div>
</div>
<div class="divTableBody" id="fileGrid">
</div>
</div>
<div class="blueTableouterTableFooter"><div class="tableFootStyle"><div class="links"><a href="#">&laquo;</a><a class="active" href="#">1</a><a href="#">2</a><a href="#">3</a><a href="#">4</a><a href="#">&raquo;</a></div></div></div>
</div>
</div>
</div>
</div>`; 
this.setButtonsEventHandlers();
this.getAllItem();
  } 

privatesetButtonsEventHandlers(): void { 
constwebPart: NoFrameworkCrudWebPart = this; 
this.domElement.querySelector('button.create-Button').addEventListener('click', () => { webPart.SaveItem(); }); 
this.domElement.querySelector('button.update-Button').addEventListener('click', () => { webPart.updateItem(); }); 
this.domElement.querySelector('button.read-Button').addEventListener('click', () => { webPart.ClearMethod(); }); 
  }
// Start Get All Data From SharePoint  List
privategetAllItem(){ 
this.context.spHttpClient.get(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.Listname}')/items?$orderby=Created desc`, 
           SPHttpClient.configurations.v1, 
           { 
headers: { 
'Accept': 'application/json;odata=nometadata', 
'odata-version': ''
             } 
           })
           .then((response: SPHttpClientResponse)=> { 
returnresponse.json(); 
           }) 
           .then((item):void => {
debugger;
varlen = item.value.length
var txt = "";
if(len>0){
for(vari=0;i<len;i++){

txt += '<div class="divTableRow" ><div class="divTableCell">'+item.value[i].Title +'</div><div class="divTableCell">'+item.value[i].NameF +'</div><div class="divTableCell">'+item.value[i].Gender+'</div>' +
'<div class="divTableCell">'+item.value[i].Department+'</div><div class="divTableCell">'+item.value[i].City+'</div><div class="divTableCell">'+"<a id='" + item.value[i].ID + "' href='#' class='EditFileLink'>Edit</a>"+'</div><div class="divTableCell">'+"<a id='" + item.value[i].ID + "' href='#' class='DeleteLink'>Delete</a>"+'</div></div>';
                 }
if(txt != ""){
document.getElementById("fileGrid").innerHTML = txt;
                  }

//  delete Start Bind The Event into anchor Tag
letlistItems = document.getElementsByClassName("DeleteLink")
for(let j:number = 0; j<listItems.length; j++){
listItems[j].addEventListener('click', (event) => {
this.DeleteItemClicked(event);
                    });
                  }
// End Bind The Event into anchor Tag

//  Edit Start Bind The Event into anchor Tag
letEditlistItems = document.getElementsByClassName("EditFileLink")
for(let j:number = 0; j<EditlistItems.length; j++){
EditlistItems[j].addEventListener('click', (event) => {
this.UpdateItemClicked(event);
                      });
                    }
// End Bind The Event into anchor Tag
             }
// debugger;

//console.log(item.Title) ;

           }, (error: any): void => { 
alert(error);
           }); 
      }
// End Get All Data From SharePoint  List
//Start Save Item in SharerPoint List
privateSaveItem(): void { 
debugger;
if(document.getElementById('idTitle')["value"]=="")
    {
alert('Required the Title !!!')
return;
    }
if(document.getElementById('idfname')["value"]=="")
    {
alert('Required the Name !!!')
return;
    }
if(document.getElementById('idgender')["value"]=="")
    {
alert('Required the Gender !!!')
return;
    }
if(document.getElementById('idDepart')["value"]=="")
    {
alert('Required the Department !!!')
return;
    }
if(document.getElementById('idCity')["value"]=="")
    {
alert('Required the City !!!')
return;
    }
const body: string = JSON.stringify({ 
'Title': document.getElementById('idTitle')["value"],
'NameF': document.getElementById('idfname')["value"],
'Gender': document.getElementById('idgender')["value"],
'Department': document.getElementById('idDepart')["value"],
'City': document.getElementById('idCity')["value"]    
    });  
this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.Listname}')/items`, 
    SPHttpClient.configurations.v1, 
    { 
headers: { 
'Accept': 'application/json;odata=nometadata', 
'Content-type': 'application/json;odata=nometadata', 
'odata-version': ''
      }, 
body: body 
    }) 
    .then((response: SPHttpClientResponse): Promise<IListItem>=> { 
returnresponse.json(); 
    }) 
    .then((item: IListItem): void => {
this.ClearMethod();
alert('Item has been successfully Saved ');
localStorage.removeItem('ItemId');
localStorage.clear();
this.getAllItem();
    }, (error: any): void => { 
alert(`${error}`); 
    }); 
  } 
//End Save Item in SharerPoint List

//Start Update Item in SharerPoint List
privateUpdateItemClicked(ev): void{
letme:any = ev.target;
this.getByIdItem(me.id);
  }
privateupdateItem(){
///alert(localStorage.getItem('ItemId')) ;
const body: string = JSON.stringify({ 
'Title': document.getElementById('idTitle')["value"],
'NameF': document.getElementById('idfname')["value"],
'Gender': document.getElementById('idgender')["value"],
'Department': document.getElementById('idDepart')["value"],
'City': document.getElementById('idCity')["value"]    
    });  
this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.Listname}')/items(${localStorage.getItem('ItemId')})`, 
          SPHttpClient.configurations.v1, 
          { 
headers: { 
'Accept': 'application/json;odata=nometadata', 
'Content-type': 'application/json;odata=nometadata', 
'odata-version': '', 
'IF-MATCH': '*', 
'X-HTTP-Method': 'MERGE'
            }, 
body: body
          }) 
          .then((response: SPHttpClientResponse): void => { 
alert(`Item with ID: ${localStorage.getItem('ItemId')} successfully updated`);
this.ClearMethod()
localStorage.removeItem('ItemId');
localStorage.clear();
this.getAllItem();

          }, (error: any): void => { 
alert(`${error}`); 
          }); 

  } 
//End Update Item in SharerPoint List
// Delete the Items From SharePoint List
privateDeleteItemClicked(ev): void{
letme:any = ev.target;
//alert(me.id);
this.deleteItem(me.id);
  }
privatedeleteItem(Id: number){
if (!window.confirm('Are you sure you want to delete the latest item?')) { 
return; 
    } 
letetag: string = undefined; 
this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.Listname}')/items(${Id})`, 
          SPHttpClient.configurations.v1, 
          { 
headers: { 
'Accept': 'application/json;odata=nometadata', 
'Content-type': 'application/json;odata=verbose', 
'odata-version': '', 
'IF-MATCH': '*', 
'X-HTTP-Method': 'DELETE'
            } 
          })
      .then((response: SPHttpClientResponse): void => { 
alert(`Item with ID: ${Id} successfully Deleted`)

this.getAllItem();
      }, (error: any): void => { 
alert(`${error}`); 
      }); 
  } 
// End Delete the Items From SharePoint List

// Start Get Item By Id
privategetByIdItem(Id: number){ 
this.context.spHttpClient.get(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.Listname}')/items(${Id})`, 
     SPHttpClient.configurations.v1, 
     { 
headers: { 
'Accept': 'application/json;odata=nometadata', 
'odata-version': ''
       } 
     })
     .then((response: SPHttpClientResponse)=> { 
returnresponse.json(); 
     }) 
     .then((item):void => {
document.getElementById('idTitle')["value"]=item.Title;
document.getElementById('idfname')["value"]=item.NameF;
document.getElementById('idgender')["value"]=item.Gender;
document.getElementById('idDepart')["value"]=item.Department;
document.getElementById('idCity')["value"]=item.City;
localStorage.setItem('ItemId', item.Id);

     }, (error: any): void => { 
alert(error);
     }); 
}
// End Get Item By Id
// start Clear Method of input type
privateClearMethod()
{
document.getElementById('idTitle')["value"]="";
document.getElementById('idfname')["value"]="";
document.getElementById('idgender')["value"]="";
document.getElementById('idDepart')["value"]="";
document.getElementById('idCity')["value"]="";
}
// End Clear Method of input type
protectedgetPropertyPaneConfiguration(): IPropertyPaneConfiguration { 
return { 
pages: [ 
        { 
header: { 
description: strings.PropertyPaneDescription
          }, 
groups: [ 
            { 
groupName: strings.BasicGroupName, 
groupFields: [ 
PropertyPaneTextField('listname', { 
label: strings.ListNameFieldLabel
                }) 
              ] 
            } 
          ] 
        } 
      ] 
    }; 
  } 
}



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

.noFrameworkCrud {
.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;
    }
  }
}

NoFrameworkCrudWebPart.manifest.json
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "5eb68e1e-2fb9-4020-9cc5-ad8e832a6dcc",
"alias": "NoFrameworkCrudWebPart",
"componentType": "WebPart",

// The "*" signifies that the version should be taken from the package.json
"version": "*",
"manifestVersion": 2,

// If true, the component can only be installed on sites where Custom Script is allowed.
// Components that allow authors to embed arbitrary script code should set this to true.
// https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
"requiresCustomScript": false,

"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Other
"group": { "default": "Other" },
"title": { "default": "noFrameworkCrud" },
"description": { "default": "noFrameworkCrud" },
"officeFabricIconFontName": "Page",
"properties": {
"description": "noFrameworkCrud"
    }
  }]
}

IListItem.ts
exportinterfaceIListItem { 
    Title?: string; 
    Id: number; 
}

In loc Folder Check belw JS and TS File
en-us.js
define([], function() { 
return { 
"PropertyPaneDescription": "Description", 
"BasicGroupName": "Group Name", 
"ListNameFieldLabel": "List Name"
  } 
});
mystrings.d.ts
declareinterfaceINoFrameworkCrudWebPartStrings { 
PropertyPaneDescription: string; 
BasicGroupName: string; 
ListNameFieldLabel: string; 
} 
declaremodule'NoFrameworkCrudWebPartStrings' { 
const strings: INoFrameworkCrudWebPartStrings; 
export = strings; 
} 

 Copy and paste the css file below in notepad and save as styles.css Put SharePoint On Line Site Site Assets

div.blueTable {
  border: 1px solid #1C6EA4;
  background-color: #EEEEEE;
  width: 100%;
  text-align: left;
  border-collapse: collapse;
}
.divTable.blueTable .divTableCell, .divTable.blueTable .divTableHead {
  border: 1px solid #AAAAAA;
  padding: 3px 2px;
}
.divTable.blueTable .divTableBody .divTableCell {
  font-size: 13px;
}
.divTable.blueTable .divTableRow:nth-child(even) {
  background: #D0E4F5;
}
.divTable.blueTable .divTableHeading {
  background: #1C6EA4;
background: -moz-linear-gradient(top, #5592bb 0%, #327cad 66%, #1C6EA4 100%);
background: -webkit-linear-gradient(top, #5592bb 0%, #327cad 66%, #1C6EA4 100%);
background: linear-gradient(to bottom, #5592bb 0%, #327cad 66%, #1C6EA4 100%);
  border-bottom: 2px solid #444444;
}
.divTable.blueTable .divTableHeading .divTableHead {
  font-size: 15px;
  font-weight: bold;
color: #FFFFFF;
  border-left: 2px solid #D0E4F5;
}
.divTable.blueTable .divTableHeading .divTableHead:first-child {
  border-left: none;
}

.blueTable .tableFootStyle {
  font-size: 14px;
  font-weight: bold;
color: #FFFFFF;
  background: #D0E4F5;
background: -moz-linear-gradient(top, #dcebf7 0%, #d4e6f6 66%, #D0E4F5 100%);
background: -webkit-linear-gradient(top, #dcebf7 0%, #d4e6f6 66%, #D0E4F5 100%);
background: linear-gradient(to bottom, #dcebf7 0%, #d4e6f6 66%, #D0E4F5 100%);
  border-top: 2px solid #444444;
}
.blueTable .tableFootStyle {
  font-size: 14px;
}
.blueTable .tableFootStyle .links {
        text-align: right;
}
.blueTable .tableFootStyle .links a{
  display: inline-block;
  background: #1C6EA4;
color: #FFFFFF;
  padding: 2px 8px;
  border-radius: 5px;
}
.blueTable.outerTableFooter {
  border-top: none;
}
.blueTable.outerTableFooter .tableFootStyle {
  padding: 3px 5px;
}
/* DivTable.com */
.divTable{ display: table; }
.divTableRow { display: table-row; }
.divTableHeading { display: table-header-group;}
.divTableCell, .divTableHead { display: table-cell;}
.divTableHeading { display: table-header-group;}
.divTableFoot { display: table-footer-group;}
.divTableBody { display: table-row-group;}


/* Css styles for the form */

* {
    box-sizing: border-box;
}

input[type=text], select, textarea{
    width: 100%;
    padding: 12px;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
    resize: vertical;
}

label {
    padding: 12px 12px12px 0;
    display: inline-block;
}

input[type=submit] {
    background-color: #4CAF50;
color: white;
    padding: 12px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    float: right;
}

input[type=submit]:hover {
    background-color: #45a049;
}

.container {
    border-radius: 5px;
    background-color: #f2f2f2;
    padding: 20px;
}

.col-25 {
    float: left;
    width: 25%;
    margin-top: 6px;
}

.col-75 {
    float: left;
    width: 75%;
    margin-top: 6px;
}

/* Clear floats after the columns */
.row:after {
    content: "";
    display: table;
    clear: both;
}

/* Responsive layout - when the screen is less than 600px wide, make the two columns stack on top of each other instead of next to each other */
@media (max-width: 600px) {
    .col-25, .col-75, input[type=submit] {
        width: 100%;
        margin-top: 0;
    }
}

Reference Below:
http://everythingsharepoint.blogspot.com/2017/04/spfx-sharepoint-online-responsive-web.html