CRUD operations using SPFx no javascript framework in SharePoint Online

SharePoint Online: CRUD operations using SPFx no javascript framework

No comments

 1,531 total views,  106 views today

In this tutorial, we will learn about how we can do the SharePoint crud operations using the SPFx no javascript framework.

Key Highlights

  • Create the SharePoint project scaffolding
  • Verify the project scaffolding
  • Customize the code for SharePoint CRUD operation using the SPFx no javascript framework
  • SPFx Web part Project Main TS (TypeScript) File(SpcrudOperationUsingSpFxNoJavascriptFrameworkWebPart.ts)
  • Complete Code: SharePoint CRUD operation using the SPFx no Javascript framework
  • SPFx framework Render Method code
  • Code to get all items from SharePoint list using SPFx framework
  • Code to save or add the item in SharePoint List using SPFx framework
  • Code to update the item in SharePoint List using SPFx framework
  • Code to delete the item from SharePoint List using SPFx framework
  • Code to getting the SharePoint list item by ID using SPFx framework
  • Code to clear form data entry after submitting the form to SharePoint list using SPFx framework
  • The “IListItem.d.ts” and “MyAppStyle.css” file in the SharePoint SPFx Framework project
  • Source Code
  • Summary: What we have learned here?
  • See Also

We will go through this tutorial step by step and at the end of this tutorial, we will be able to see the below SPFX CRUD operation web part which renders in the browser.

SharePoint CRUD Operation using SPFx No Javascript Framework Demo
SharePoint CRUD Operation using SPFx No Javascript Framework Demo

SharePoint crud operations using SPFx no javascript framework

Step 1:  Create the SharePoint project scaffolding

  1. Open the node.js command prompt and go to your desired folder path where you want to create your project.
cd C:\Temp\SPFx
SharePoint CRUD Operation using SPFx No JavaScript Framework
SharePoint CRUD Operation using SPFx No JavaScript Framework

Note:

  • If you have installed node.js – you can use any of the commands prompts like windows command prompt, PowerShell or Node.js command prompt.

2. Create a new project folder in the above location, using the below command:

3. Run the Yeoman SharePoint Generator – to create the SharePoint project scaffolding.

yo @microsoft/sharepoint

After a few seconds, we will be asked to pass the parameters in a sequence, so in most of the parameters,  pass the default selection as-is:

  1. Accept the default spcrud-operation-using-sp-fx-no-javascript-framework-web part as your solution name, and then press the enter key.
  2. Select SharePoint Online only (latest), for Which baseline packages do you want to target for your component(s)? and press the enter key.
  3. Select Use the current folder for where do you want to place the files?
  4. Select N  for “Do you want to allow the tenant admin the choice of being able to deploy the solution to all sites immediately without
    running any feature deployment or adding apps in sites? “
  5. Select N for “Will the components in the solution require permissions to access web APIs that are unique and not shared with other components in the tenant?”
  6. Select WebPart for “Which type of client-side component to create?”

 

Notes:

We can create below three types of project in SharePoint Framework (SPFx):

  • WebPart
  • Extension
  • Library

Now in the subsequent prompts – it will ask the specific input about the web part.

1. What is your Web part name? spcrud-operation-using-sp-fx-no -javascript-framework - hit enter key
2. What is your Web part description? (spcrud-operation-using-sp-fx-no-javascript-framework description)-hit enter key
3. Which framework would you like to use? (Use arrow keys) - select No JavaScript framework

Notes:

There are three types of frameworks available, such as:

  • No JavaScript framework
  • React
  • Knockout

For this demo example, I have selected the “No JavaScript framework”. 

Finally, the yo @microsoft/sharepoint – SPFX web part project execution status will be like below:

Solution spcrud-operation-using-sp-fx-no-javascript-framework is created - Run gulp serve to play with it
Solution spcrud-operation-using-sp-fx-no-javascript-framework is created – Run gulp serve to play with it

Step 2:  Verify the project scaffolding

Run the “gulp build” and “gulp serve” command to verify the SPFx project is scaffolded successfully.

SPFx Gulp Build – run the “gulp build” command to build the project.

SPFx Gulp Build - Build target DEBUG
SPFx Gulp Build – Build target DEBUG

Office SharePoint Workbench SPFx Runtime test – to test the SPFx project run the “gulp serve” command.

SPFx Gulp Serve Command - Build target DEBUG
SPFx Gulp Serve Command – Build target DEBUG

Verify the web part renders successfully in the browser.

Note:

  • If the web part renders successfully in the browser, we can ensure the basic SPFx projected has been scaffolded successfully.
Office SharePoint Workbench SPFx Runtime test
Office SharePoint Workbench SPFx Runtime test

Step 3: Customize the code for SharePoint CRUD operation using the SPFx no javascript framework

To open the SPFx code in visual studio editor, we need to type “code .” (code single space dot).

SPFx open code in visual studio editor
SPFx open code in visual studio editor

SPFx Web part Project Main TS (TypeScript) file

For SPFx web part project, there will be a file with the web part name(.ts extension), which is the heart of the SPFx web part project – for any sort of customization we need to start here, example as below: SpcrudOperationUsingSpFxNoJavascriptFrameworkWebPart.ts

SPFx Webpart Project Main TS (TypeScript) file
SPFx Web part Project Main TS (TypeScript) file

Beginning of this file we need to import all modules to use in the project, exactly the same as “using namespaces” in the C# programming.

Complete Code: SharePoint CRUD operation using the SPFx no Javascript framework

import { Version } from '@microsoft/sp-core-library';

import {

  IPropertyPaneConfiguration,

  PropertyPaneTextField,

  PropertyPaneCheckbox,

  PropertyPaneDropdown,

  PropertyPaneToggle

} from '@microsoft/sp-property-pane';

import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';

import { escape } from '@microsoft/sp-lodash-subset';

import {IListItem} from './loc/IListItem';

import styles from './SpcrudOperationUsingSpFxNoJavascriptFrameworkWebPart.module.scss';

import * as strings from 'SpcrudOperationUsingSpFxNoJavascriptFrameworkWebPartStrings';

import { SPComponentLoader } from'@microsoft/sp-loader';

import './loc/css/MyAppStyle.css';

import

 {

  SPHttpClient,

  SPHttpClientResponse   

} from '@microsoft/sp-http';

import

 {

  Environment,

  EnvironmentType

} from '@microsoft/sp-core-library';

export interface ISPLists {

  value: ISPList[];

}

export interface ISPList {

  Title: string;

  

}

export interface ISpcrudOperationUsingSpFxNoJavascriptFrameworkWebPartProps {

  description: string;

}

export default class SpcrudOperationUsingSpFxNoJavascriptFrameworkWebPart extends BaseClientSideWebPart <ISpcrudOperationUsingSpFxNoJavascriptFrameworkWebPartProps>

{

  private listItemEntityTypeName: string = undefined; 

  private Listname :string="CustomerDetails";

  private _getListData(): Promise<ISPLists>

   {

    return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + "/_api/web/lists/GetByTitle('Conros Products')/Items",SPHttpClient.configurations.v1)

        .then((response: SPHttpClientResponse) => {

        return response.json();

        });

    }

    private _renderListAsync(): void

     {

    

      if (Environment.type == EnvironmentType.SharePoint || 

               Environment.type == EnvironmentType.ClassicSharePoint) {

       this._getListData()

         .then((response) => {

           this._renderList(response.value);

         });

     }

   }

   private _renderList(items: ISPList[]): void 

   {

    let html: string = '<table border=1 width=100% style="border-collapse: collapse;">';

    html += '<th>Title</th> <th>Product Code</th><th>Product Description</th>';

    items.forEach((item: ISPList) => {

      html += `

      <tr>            

          <td>${item.Title}</td>         

          

          </tr>

          `;

    });

    html += '</table>';

  

    const listContainer: Element = this.domElement.querySelector('#spListContainer');

    listContainer.innerHTML = html;

  }

  public render(): void { 

    this.domElement.innerHTML = ` 

    <div class="${styles.spcrudOperationUsingSpFxNoJavascriptFramework}">

    <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 

    </h2>

    <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="idCustName" 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="idCustGender" name="gender" placeholder="Gender..">

    </div>

    </div>

    <div class="row">

    <div class="col-25">

    <label for="country">Customer Number</label>

    </div>

    <div class="col-75">

    <input type="text" id="idCustNumber" name="lname" placeholder="Customer Number..">

    </div>

    </div>

    <div class="row">

    <div class="col-25">

    <label for="subject">CustCategory</label>

    </div>

    <div class="col-75">

    <input type="text" id="idCustCategory" name="gender" placeholder="Customer Category..">

    </div>

    </div>

    <div class="row">

    <div class="col-25">

    <label for="CustMobileNumber">Customer Mobile Number</label>

    </div>

    <div class="col-75">

    <input type="text" id="idCustMobileNumber" name="CustMobileNumber" placeholder="Customer Mobile Number.">

    </div>

    </div>

    <div class="row">

    <div class="col-25">

    <label for="CustCity">Customer City</label>

    </div>

    <div class="col-75">

    <input type="text" id="idCustCity" name="CustCity" placeholder="Customer City.">

    </div>

    </div>

    <div class="row">

    <div class="col-25">

    <label for="Remark">Remark</label>

    </div>

    <div class="col-75">

    <input type="text" id="idRemark" name="Remark" placeholder="Remark.">

    </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">Number</div>

    <div class="divTableHead">Category</div>

    <div class="divTableHead">Mobile No</div>

    <div class="divTableHead">City</div>

    <div class="divTableHead">Remark</div>    

    </div>

    </div>

    <div class="divTableBody" id="fileGrid" border="1">

    </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._renderListAsync();

  this.setButtonsEventHandlers();

  this.getAllItemsFromList();

}

private setButtonsEventHandlers(): void

{ 

 const webPart:SpcrudOperationUsingSpFxNoJavascriptFrameworkWebPart = this; 

 this.domElement.querySelector('button.create-Button').addEventListener('click', () => { webPart.SaveItemToList(); }); 

 this.domElement.querySelector('button.update-Button').addEventListener('click', () => { webPart.updateItemInList(); }); 

}

// Start Get All Data From SharePoint List

private getAllItemsFromList()

{ 

  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)=> { 

  return response.json(); 

             }) 

             .then((item):void => {

  debugger;

  var len = item.value.length;

  var txt = "";

  if(len>0){

  for(var i=0;i<len;i++){

  

  txt += '<div class="divTableRow" ><div class="divTableCell">'+item.value[i].Title +'</div><div class="divTableCell">'+item.value[i].CustName+'</div><div class="divTableCell">'+item.value[i].CustGender+'</div>' +

  '<div class="divTableCell">'+item.value[i].CustNumber+'</div><div class="divTableCell">'+item.value[i].CustCategory+'</div><div class="divTableCell">'+item.value[i].CustMobileNumber+'</div><div class="divTableCell">'+item.value[i].CustCity+'</div><div class="divTableCell">'+item.value[i].Remark+'</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

  let listItems = 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

  let EditlistItems = 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

private SaveItemToList(): void { 

  debugger;

  if(document.getElementById('idTitle')["value"]=="")

      {

  alert('Required the Title !!!');

  return;

      }

  if(document.getElementById('idCustName')["value"]=="")

      {

  alert('Required the Customer Name !!!');

  return;

      }

  if(document.getElementById('idCustGender')["value"]=="")

      {

  alert('Required the Customer Gender !!!');

  return;

      }

  if(document.getElementById('idCustNumber')["value"]=="")

      {

  alert('Required the Customer Number !!!');

  return;

      }

  if(document.getElementById('idCustCategory')["value"]=="")

      {

  alert('Required the Category !!!');

  return;

      }

      if(document.getElementById('idCustMobileNumber')["value"]=="")

      {

  alert('Required the Customer Mobile Number !!!');

  return;

      }

      if(document.getElementById('idCustCity')["value"]=="")

      {

  alert('Required the Customer City !!!');

  return;

      }

      /* 

      if(document.getElementById('idRemark')["value"]=="")

      {

  alert('Required the Remark !!!')

  return;

      }

      */

  const body: string = JSON.stringify({ 

  'Title': document.getElementById('idTitle')["value"],

  'CustName': document.getElementById('idCustName')["value"],

  'CustGender': document.getElementById('idCustGender')["value"],

  'CustNumber': document.getElementById('idCustNumber')["value"],

  'CustCategory': document.getElementById('idCustCategory')["value"],

  'CustMobileNumber': document.getElementById('idCustMobileNumber')["value"], 

  'CustCity': document.getElementById('idCustCity')["value"],

  'Remark': document.getElementById('idRemark')["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>=> { 

  return response.json(); 

      }) 

      .then((item: IListItem): void => {

  this.ClearMethodInForm();

  alert('Item has been successfully Saved ');

  localStorage.removeItem('ItemId');

  localStorage.clear();

  this.getAllItemsFromList();

      }, (error: any): void => { 

  alert(`${error}`); 

      }); 

    } 

  //End Save Item in SharerPoint List

  //Start Update Item in SharerPoint List

private UpdateItemClicked(ev): void{

  let me:any = ev.target;

  this.getItemByIDFromList(me.id);

    }

  private updateItemInList(){

  ///alert(localStorage.getItem('ItemId')) ;

  const body: string = JSON.stringify({ 

    'Title': document.getElementById('idTitle')["value"],

    'CustName': document.getElementById('idCustName')["value"],

    'CustGender': document.getElementById('idCustGender')["value"],

    'CustNumber': document.getElementById('idCustNumber')["value"],

    'CustCategory': document.getElementById('idCustCategory')["value"],

    'CustMobileNumber': document.getElementById('idCustMobileNumber')["value"], 

    'CustCity': document.getElementById('idCustCity')["value"],

    'Remark': document.getElementById('idRemark')["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.ClearMethodInForm();

  localStorage.removeItem('ItemId');

  localStorage.clear();

  this.getAllItemsFromList();

  

            }, (error: any): void => { 

  alert(`${error}`); 

            }); 

  

    } 

  //End Update Item in SharerPoint List

  // Delete the Items From SharePoint List

private DeleteItemClicked(ev): void{

  let me:any = ev.target;

  //alert(me.id);

  this.deleteItemfromList(me.id);   

    }

  private deleteItemfromList(Id: number){

  if (!window.confirm('Are you sure you want to delete the latest item?')) { 

  return; 

      } 

  let etag: 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.getAllItemsFromList();

        }, (error: any): void => { 

  alert(`${error}`); 

        }); 

    } 

  // End Delete the Items From SharePoint List

// Start Get Item By Id

private getItemByIDFromList(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)=> { 

  return response.json(); 

       }) 

       .then((item):void => {

  document.getElementById('idTitle')["value"]=item.Title;

  document.getElementById('idCustName')["value"]=item.CustName;

  document.getElementById('idCustGender')["value"]=item.CustGender;

  document.getElementById('idCustNumber')["value"]=item.CustNumber;

  document.getElementById('idCustCategory')["value"]=item.CustCategory;

  document.getElementById('idCustMobileNumber')["value"]=item.CustMobileNumber;

  document.getElementById('idCustCity')["value"]=item.CustCity;

  document.getElementById('idRemark')["value"]=item.Remark;

  localStorage.setItem('ItemId', item.Id);

  

       }, (error: any): void => { 

  alert(error);

       }); 

  }

  // End Get Item By Id

// start Clear Method of input type

private ClearMethodInForm()

{

  document.getElementById('idTitle')["value"]="";

  document.getElementById('idCustName')["value"]="";

  document.getElementById('idCustGender')["value"]="";

  document.getElementById('idCustNumber')["value"]="";

  document.getElementById('idCustCategory')["value"]="";

  document.getElementById('idCustMobileNumber')["value"]="";

  document.getElementById('idCustCity')["value"]="";

  document.getElementById('idRemark')["value"]="";

}

// End Clear Method of input type

protected get dataVersion(): Version

   {

  return Version.parse('1.0');

}

protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {

  return {

    pages: [

      {

        header:

         {

          description: strings.PropertyPaneDescription

        },

        groups: [

          {

            groupName: strings.BasicGroupName,

           

            

            groupFields: [

              PropertyPaneTextField('listname', { 

                label: strings.ListNameFieldLabel

                                }),

            PropertyPaneTextField('description', {

              label: 'Description'

            }),

            PropertyPaneTextField('test', {

              label: 'Multi-line Text Field',

              multiline: true

            }),

            PropertyPaneCheckbox('test1', {

              text: 'Checkbox'

            }),

            PropertyPaneDropdown('test2', {

              label: 'Dropdown',

              options: [

                { key: '1', text: 'One' },

                { key: '2', text: 'Two' },

                { key: '3', text: 'Three' },

                { key: '4', text: 'Four' }

              ]}),

              PropertyPaneToggle('test3', {

                label: 'Toggle',

                onText: 'On',

                offText: 'Off'

            })

            

          ]

          }

        ]

      }

    ]

  };

}

  

}

SPFx framework Render Method code

Below is the Render method which does the job to render the web part in the browser.

public render(): void { 

    this.domElement.innerHTML = ` 

    <div class="${styles.spcrudOperationUsingSpFxNoJavascriptFramework}">

    <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 

    </h2>

    <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="idCustName" 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="idCustGender" name="gender" placeholder="Gender..">

    </div>

    </div>

    <div class="row">

    <div class="col-25">

    <label for="country">Customer Number</label>

    </div>

    <div class="col-75">

    <input type="text" id="idCustNumber" name="lname" placeholder="Customer Number..">

    </div>

    </div>

    <div class="row">

    <div class="col-25">

    <label for="subject">CustCategory</label>

    </div>

    <div class="col-75">

    <input type="text" id="idCustCategory" name="gender" placeholder="Customer Category..">

    </div>

    </div>

    <div class="row">

    <div class="col-25">

    <label for="CustMobileNumber">Customer Mobile Number</label>

    </div>

    <div class="col-75">

    <input type="text" id="idCustMobileNumber" name="CustMobileNumber" placeholder="Customer Mobile Number.">

    </div>

    </div>

    <div class="row">

    <div class="col-25">

    <label for="CustCity">Customer City</label>

    </div>

    <div class="col-75">

    <input type="text" id="idCustCity" name="CustCity" placeholder="Customer City.">

    </div>

    </div>

    <div class="row">

    <div class="col-25">

    <label for="Remark">Remark</label>

    </div>

    <div class="col-75">

    <input type="text" id="idRemark" name="Remark" placeholder="Remark.">

    </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">Number</div>

    <div class="divTableHead">Category</div>

    <div class="divTableHead">Mobile No</div>

    <div class="divTableHead">City</div>

    <div class="divTableHead">Remark</div>    

    </div>

    </div>

    <div class="divTableBody" id="fileGrid" border="1">

    </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._renderListAsync();

  this.setButtonsEventHandlers();

  this.getAllItemsFromList();

}

Code to get all items from SharePoint list using SPFx framework

Using the below typescript code, we can read the SharePoint list items.

// Start Get All Data From SharePoint List

private getAllItemsFromList()

{ 

  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)=> { 

  return response.json(); 

             }) 

             .then((item):void => {

  debugger;

  var len = item.value.length;

  var txt = "";

  if(len>0){

  for(var i=0;i<len;i++){

  

  txt += '<div class="divTableRow" ><div class="divTableCell">'+item.value[i].Title +'</div><div class="divTableCell">'+item.value[i].CustName+'</div><div class="divTableCell">'+item.value[i].CustGender+'</div>' +

  '<div class="divTableCell">'+item.value[i].CustNumber+'</div><div class="divTableCell">'+item.value[i].CustCategory+'</div><div class="divTableCell">'+item.value[i].CustMobileNumber+'</div><div class="divTableCell">'+item.value[i].CustCity+'</div><div class="divTableCell">'+item.value[i].Remark+'</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

  let listItems = 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

  let EditlistItems = 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

 

Code to save or add the item in SharePoint List using SPFx framework

//Start Save Item in SharerPoint List

private SaveItemToList(): void { 

  debugger;

  if(document.getElementById('idTitle')["value"]=="")

      {

  alert('Required the Title !!!');

  return;

      }

  if(document.getElementById('idCustName')["value"]=="")

      {

  alert('Required the Customer Name !!!');

  return;

      }

  if(document.getElementById('idCustGender')["value"]=="")

      {

  alert('Required the Customer Gender !!!');

  return;

      }

  if(document.getElementById('idCustNumber')["value"]=="")

      {

  alert('Required the Customer Number !!!');

  return;

      }

  if(document.getElementById('idCustCategory')["value"]=="")

      {

  alert('Required the Category !!!');

  return;

      }

      if(document.getElementById('idCustMobileNumber')["value"]=="")

      {

  alert('Required the Customer Mobile Number !!!');

  return;

      }

      if(document.getElementById('idCustCity')["value"]=="")

      {

  alert('Required the Customer City !!!');

  return;

      }

      /* 

      if(document.getElementById('idRemark')["value"]=="")

      {

  alert('Required the Remark !!!')

  return;

      }

      */

  const body: string = JSON.stringify({ 

  'Title': document.getElementById('idTitle')["value"],

  'CustName': document.getElementById('idCustName')["value"],

  'CustGender': document.getElementById('idCustGender')["value"],

  'CustNumber': document.getElementById('idCustNumber')["value"],

  'CustCategory': document.getElementById('idCustCategory')["value"],

  'CustMobileNumber': document.getElementById('idCustMobileNumber')["value"], 

  'CustCity': document.getElementById('idCustCity')["value"],

  'Remark': document.getElementById('idRemark')["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>=> { 

  return response.json(); 

      }) 

      .then((item: IListItem): void => {

  this.ClearMethodInForm();

  alert('Item has been successfully Saved ');

  localStorage.removeItem('ItemId');

  localStorage.clear();

  this.getAllItemsFromList();

      }, (error: any): void => { 

  alert(`${error}`); 

      }); 

    } 

  //End Save Item in SharerPoint List

Code to update the item in SharePoint List using SPFx framework

//Start Update Item in SharerPoint List

private UpdateItemClicked(ev): void{

  let me:any = ev.target;

  this.getItemByIDFromList(me.id);

    }

  private updateItemInList(){

  ///alert(localStorage.getItem('ItemId')) ;

  const body: string = JSON.stringify({ 

    'Title': document.getElementById('idTitle')["value"],

    'CustName': document.getElementById('idCustName')["value"],

    'CustGender': document.getElementById('idCustGender')["value"],

    'CustNumber': document.getElementById('idCustNumber')["value"],

    'CustCategory': document.getElementById('idCustCategory')["value"],

    'CustMobileNumber': document.getElementById('idCustMobileNumber')["value"], 

    'CustCity': document.getElementById('idCustCity')["value"],

    'Remark': document.getElementById('idRemark')["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.ClearMethodInForm();

  localStorage.removeItem('ItemId');

  localStorage.clear();

  this.getAllItemsFromList();

  

            }, (error: any): void => { 

  alert(`${error}`); 

            }); 

  

    } 

  //End Update Item in SharerPoint List

Code to delete the item from SharePoint List using SPFx framework

// Delete the Items From SharePoint List

private DeleteItemClicked(ev): void{

  let me:any = ev.target;




  this.deleteItemfromList(me.id);   

    }

  private deleteItemfromList(Id: number){

  if (!window.confirm('Are you sure you want to delete the latest item?')) { 

  return; 

      } 

  let etag: 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.getAllItemsFromList();

        }, (error: any): void => { 

  alert(`${error}`); 

        }); 

    } 

  // End Delete the Items From SharePoint List

Code to getting the SharePoint list item by ID using SPFx framework

// Start Get Item By Id

private getItemByIDFromList(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)=> { 

  return response.json(); 

       }) 

       .then((item):void => {

  document.getElementById('idTitle')["value"]=item.Title;

  document.getElementById('idCustName')["value"]=item.CustName;

  document.getElementById('idCustGender')["value"]=item.CustGender;

  document.getElementById('idCustNumber')["value"]=item.CustNumber;

  document.getElementById('idCustCategory')["value"]=item.CustCategory;

  document.getElementById('idCustMobileNumber')["value"]=item.CustMobileNumber;

  document.getElementById('idCustCity')["value"]=item.CustCity;

  document.getElementById('idRemark')["value"]=item.Remark;

  localStorage.setItem('ItemId', item.Id);

  

       }, (error: any): void => { 

  alert(error);

       }); 

  }

  // End Get Item By Id

Code to clear form data entry after submitting the form to SharePoint list using SPFx framework

//start clear method for form data entry

private ClearMethodInForm()

{

  document.getElementById('idTitle')["value"]="";

  document.getElementById('idCustName')["value"]="";

  document.getElementById('idCustGender')["value"]="";

  document.getElementById('idCustNumber')["value"]="";

  document.getElementById('idCustCategory')["value"]="";

  document.getElementById('idCustMobileNumber')["value"]="";

  document.getElementById('idCustCity')["value"]="";

  document.getElementById('idRemark')["value"]="";

}
//Endclear method for form data entry

The “IListItem.d.ts” and “MyAppStyle.css” file in the SharePoint SPFx Framework project

The “IListItem.d.ts” and “MyAppStyle.css” file need to added to the project in order to render the web part successfully. Example below:

IListItem.d.ts file in SharePoint SPFx Framework project
IListItem.d.ts file in SharePoint SPFx Framework project

Source Code

The above source code is available in the GitHub, you may download from here.

Summary: What we have learned here?

Thus in this article, we have learned how we can do the CRUD operation in SharePoint online using the SPFx no javascript framework.

See Also

You may also like the below SharePoint SPFx articles:

Free download SharePoint Online & Office 365 Administration eBook(238 Pages)

Get the PDF eBook from here:




 

 
FREE DOWNLOAD

Send download link to:

Subscribe to get exclusive content and recommendations every month. You can unsubscribe anytime.