Spfx Crud Operations with Dynamic Controls (PNPJS)

Spfx Crud Operations with Dynamic Controls (PNPJS)

 
Open a command prompt. Create a directory for the SPFx solution.
 
md spfx-pnp-Crud
 
Navigate to the above-created directory.
 
cd spfx-pnp-Crud
 
Run the Yeoman SharePoint Generator to create the solution.
 
yo @microsoft/sharepoint
 

Solution Name

 
Hit Enter to have default name (spfx-pnp-DropDown in this case) or type in any other name for your solution.
 
Selected choice - Hit Enter
 

Target for the component

 
Here, we can select the target environment where we are planning to deploy the client web part, i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
 
Selected Choice: SharePoint Online only (latest)
 

Place of files

 
We may choose to use the same folder or create a subfolder for our solution.
 
Selected Choice: Same folder
 
Deployment option
 
Selecting Y will allow the app to deployed instantly to all sites and will be accessible everywhere.
 
Selected Choice: N (install on each site explicitly)
 

Permissions to access web APIs

 
Choose if the components in the solution require permission to access web APIs that are unique and not shared with other components in the tenant.
 
Selected Choice: N (solution contains unique permissions)

 
Type of client-side component to create

 
We can choose to create a client-side web part or an extension. Choose the web part option.
 
Selected Choice: WebPart
 
Web part name
 
Hit Enter to select the default name or type in any other name.
 
Selected Choice: SpfxDynamicCOntrols
 
Web part description
 
Hit Enter to select the default description or type in any other value.
 

Framework to use

 
Select any JavaScript framework to develop the component. Available choices are - No JavaScript Framework, React, and Knockout.
 
Selected Choice: React
 
Yeoman generator will perform a scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.
 
Once the scaffolding process is completed, lock down the version of the project dependencies by running the below command.
 
npm shrinkwrap
 
In the command prompt, type the below command to open the solution in the code editor of your choice.
 
NPM Packages Used,
 
On the command prompt, run the below command.
 
npm i @pnp/logging @pnp/common @pnp/odata @pnp/sp --save
for Pollyfills
npm install --save @pnp/polyfill-ie11
 
in SpfxDynamicCOntrolsWebPart.ts
  1. import "@pnp/polyfill-ie11";    
  2. import { sp, Web } from '@pnp/sp';     
  3. export interface ISpfxDynamicCOntrolsWebPartProps {    
  4.   description: string;    
  5. }     
  6. export default class SpfxDynamicCOntrolsWebPart extends BaseClientSideWebPart<ISpfxDynamicCOntrolsWebPartProps> {    
  7.   protected onInit(): Promise<void> {    
  8.     return new Promise<void>((resolve: () => void, reject: (error?: any) => void): void => {    
  9.       sp.setup({    
  10.         sp: {    
  11.           headers: {    
  12.             "Accept""application/json; odata=nometadata"    
  13.           }    
  14.         }    
  15.       });    
  16.       resolve();    
  17.     });    
  18.   }    
  19.   public render(): void {    
  20.     const element: React.ReactElement<ISpfxDynamicCOntrolsProps > = React.createElement(    
  21.       SpfxDynamicCOntrols,    
  22.       {    
  23.         description: this.properties.description,    
  24.         context: this.context      
  25.       }    
  26.     );    
  27.     ReactDom.render(element, this.domElement);    
  28.   }    
  29.   protected onDispose(): void {    
  30.     ReactDom.unmountComponentAtNode(this.domElement);    
  31.   }    
  32.   protected get dataVersion(): Version {    
  33.     return Version.parse('1.0');    
  34.   }    
  35.   protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {    
  36.     return {    
  37.       pages: [    
  38.         {    
  39.           header: {    
  40.             description: strings.PropertyPaneDescription    
  41.           },    
  42.           groups: [    
  43.             {    
  44.               groupName: strings.BasicGroupName,    
  45.               groupFields: [    
  46.                 PropertyPaneTextField('description', {    
  47.                   label: strings.DescriptionFieldLabel    
  48.                 })    
  49.               ]    
  50.             }    
  51.           ]    
  52.         }    
  53.       ]    
  54.     };    
  55.   }    
  56. }  
in SpfxDynamicCOntrols.ts
  1. import { ISpfxDynamicCOntrolsState } from './ISpfxDynamicCOntrolsState';    
  2. import * as $ from 'jquery';    
  3. require('./Styles/capstatus.css');    
  4. let ProjectMapId:any;    
  5. var search = window.location.search;    
  6. var params = new URLSearchParams(search);    
  7. var MYProjectname = params.get('ProjectName');    
  8. var managerlistid: number;    
  9. import { sp, Web } from '@pnp/sp';     
  10. export default class SpfxDynamicCOntrols extends React.Component<ISpfxDynamicCOntrolsProps, ISpfxDynamicCOntrolsState> {    
  11.   constructor(props: ISpfxDynamicCOntrolsProps, state: ISpfxDynamicCOntrolsState) {    
  12.     super(props);    
  13.     this.state = {    
  14.       Projectstatus: [{ mymilestone: "", myscore: "", id: "",Forcastedate:"",Actualdate:"",TgtResDate:"" }]       
  15.     };    
  16.     this.fetchdatas = this.fetchdatas.bind(this);    
  17.     this.AddProject = this.AddProject.bind(this);    
  18.     this.updateproject = this.updateproject.bind(this);    
  19.     this.AddProgram = this.AddProgram.bind(this);    
  20.     this.UpdateProgram = this.UpdateProgram.bind(this);    
  21.     if (MYProjectname)    
  22.         this.fetchdatas();    
  23.   }    
  24.   private mybutton() {    
  25.     if (!MYProjectname) {    
  26.       return <button    
  27.         onClick={this.AddProgram}>     
  28.         Add Project    
  29.       </button>;    
  30.     } else {    
  31.       return <button    
  32.       onClick={() => this.UpdateProgram()}>    
  33.         Update Project    
  34.     </button>;    
  35.     }    
  36.   }    
  37.   private createUI() {    
  38.     let widthstyle = {    
  39.       width:"100%"    
  40.     };    
  41.     let heightstyle = {    
  42.       width:"100%"    
  43.     };    
  44.     return this.state.Projectstatus.map((el, i) => (    
  45. <tr  key={i}>    
  46.               <td><input type="text" style={widthstyle} mycustomattribute={el.id || ''} placeholder="MileStone" name="mymilestone" value={el.mymilestone || ''} onChange={this.handleChange.bind(this, i)}/></td>    
  47.               <td><input type="text" style={widthstyle} mycustomattribute={el.id || ''} placeholder="Percentage" name="myscore" value={el.myscore || ''} onChange={this.handleChange.bind(this, i)}/></td>    
  48.               <td><input type="text" style={widthstyle} mycustomattribute={el.id || ''} placeholder="Forcastedate" name="Forcastedate" value={el.Forcastedate || ''} onChange={this.handleChange.bind(this, i)}/></td>    
  49.               <td><input type="text" style={widthstyle} mycustomattribute={el.id || ''} placeholder="Actualdate" name="Actualdate" value={el.Actualdate || ''} onChange={this.handleChange.bind(this, i)}/></td>    
  50.               <td><input type="text" style={widthstyle} mycustomattribute={el.id || ''} placeholder="TgtResDate" name="TgtResDate" value={el.TgtResDate || ''} onChange={this.handleChange.bind(this, i)}/></td>    
  51.               <td><span><a href="" mycustomattribute={el.id || ''} onClick={(e) => {this.removeClick(e,this, i, el.id)}}>-</a></span></td>    
  52.               </tr>    
  53.     ));    
  54.   }    
  55.   private handleChange(i, e) {    
  56.     const { name, value } = e.target;    
  57.     let Projectstatus = [...this.state.Projectstatus];    
  58.     Projectstatus[i] = { ...Projectstatus[i], [name]: value };    
  59.     this.setState({ Projectstatus });    
  60.   }    
  61.   private addClick() {    
  62.     this.setState(prevState => ({    
  63.       Projectstatus: [...prevState.Projectstatus, { mymilestone: "", myscore: "", id: "",Forcastedate:"",Actualdate:"",TgtResDate:"" }]    
  64.     }));    
  65.   }    
  66.   private removeClick(event,mythis,i, delid) {    
  67.     event.preventDefault();    
  68.     // var delid=Number($(this).attr("ProjectStatus"));    
  69.     if (MYProjectname) {    
  70.       let list = sp.web.lists.getByTitle("ProjectStatus");    
  71.       list.items.getById(delid).delete().then(_ => {    
  72.         console.log("Deleted");    
  73.       });    
  74.     }    
  75.     let Projectstatus = [...this.state.Projectstatus];    
  76.     Projectstatus.splice(i, 1);    
  77.     this.setState({ Projectstatus });    
  78.   }    
  79.   private async AddProject(myid:number) {    
  80.     const web = new Web(this.props.context.pageContext.web.absoluteUrl);    
  81.     const batch = web.createBatch();    
  82.     const list = web.lists.getByTitle("ProjectStatus");    
  83.     const entityTypeFullName = await list.getListItemEntityTypeFullName();    
  84.     for (let k = 0; k < this.state.Projectstatus.length; k++) {    
  85.       list.items.inBatch(batch).add({    
  86.         ProjectNameId: myid,    
  87.         MileStone:this.state.Projectstatus[k].mymilestone,    
  88.         PercentageComplete: this.state.Projectstatus[k].myscore,    
  89.         ForcastDate: this.state.Projectstatus[k].Forcastedate,    
  90.         ActualDate: this.state.Projectstatus[k].Actualdate,    
  91.         TargetResolutionDate: this.state.Projectstatus[k].TgtResDate    
  92.       }, entityTypeFullName).then(b => {       
  93.       });    
  94.     }    
  95.     batch.execute().then(() => {    
  96.     });    
  97.   }    
  98.   private async updateproject() {    
  99.     const web = new Web(this.props.context.pageContext.web.absoluteUrl);    
  100.     const batch = web.createBatch();    
  101.     const list = web.lists.getByTitle("ProjectStatus");    
  102.     const entityTypeFullName = await list.getListItemEntityTypeFullName();    
  103.     for (let k = 0; k < this.state.Projectstatus.length; k++) {    
  104.       if (!this.state.Projectstatus[k].id) {    
  105.         list.items.inBatch(batch).add({    
  106.           ProjectNameId: managerlistid,    
  107.           MileStone: this.state.Projectstatus[k].mymilestone,    
  108.           PercentageComplete:this.state.Projectstatus[k].myscore,    
  109.           ForcastDate: this.state.Projectstatus[k].Forcastedate,    
  110.           ActualDate: this.state.Projectstatus[k].Actualdate,    
  111.           TargetResolutionDate: this.state.Projectstatus[k].TgtResDate    
  112.         }, entityTypeFullName).then(b => {    
  113.           // console.log(b);    
  114.         });    
  115.       }    
  116.       else {    
  117.         list.items.inBatch(batch).getById(this.state.Projectstatus[k].id).update({    
  118.           ProjectNameId:managerlistid,    
  119.           MileStone: this.state.Projectstatus[k].mymilestone,    
  120.           PercentageComplete: this.state.Projectstatus[k].myscore,    
  121.           ForcastDate: this.state.Projectstatus[k].Forcastedate,    
  122.           ActualDate: this.state.Projectstatus[k].Actualdate,    
  123.           TargetResolutionDate: this.state.Projectstatus[k].TgtResDate    
  124.         }).then(b => {    
  125.           // console.log(b);    
  126.         });    
  127.       }    
  128.     }    
  129.     batch.execute().then(() => console.log("All done!"));    
  130.     // event.preventDefault();    
  131.   }    
  132.   private fetchdatas() {    
  133.     var reg1 = new RegExp('<div class=\"ExternalClass[0-9A-F]+\">', "");    
  134.     var reg2 = new RegExp('</div>$'"");    
  135.     const web = new Web(this.props.context.pageContext.web.absoluteUrl);    
  136.     //const batch1 = web.createBatch();    
  137.     const list1 = web.lists.getByTitle("Program");    
  138.     list1.items.select('Id,ProgramName').filter("ProgramName eq '" + MYProjectname + "'").get().then(r => {       
  139.       managerlistid = r[0].Id;    
  140.       $("#ProjectName").val(r[0].ProgramName);    
  141.     });    
  142.     const list2 = web.lists.getByTitle("ProjectStatus");    
  143.  let FetchProjectDetails = [];    
  144.      list2.items.select('Id,MileStone,PercentageComplete,ForcastDate,ActualDate,TargetResolutionDate').filter("ProjectName/ProgramName eq '" + MYProjectname + "'").top(5000).get().then(r => {    
  145.       for (let i = 0; i < r.length; i++) {    
  146.         FetchProjectDetails.push({    
  147.           mymilestone: r[i].MileStone,    
  148.           myscore: r[i].PercentageComplete,    
  149.           id: r[i].Id,    
  150.           Forcastedate:r[i].ForcastDate,    
  151.           Actualdate:r[i].ActualDate,    
  152.           TgtResDate:r[i].TargetResolutionDate    
  153.         });    
  154.       }    
  155.       this.setState({ Projectstatus: FetchProjectDetails });    
  156.     });    
  157.   }      
  158.   public render(): React.ReactElement<ISpfxDynamicCOntrolsProps> {         
  159.     return (    
  160.       <div className="wrapper">    
  161.       <div className="container">    
  162.         <div className="program_list">    
  163.         <div>    
  164.             <div><label>Program Name:</label></div>    
  165.             <div><input className="input" type="text" id="ProjectName" /></div>    
  166.           </div>    
  167.         </div>    
  168.         <div className="milestone">    
  169.           <table>    
  170.           <tbody>    
  171.               <tr>    
  172.               <th>Milestone Title</th>    
  173.               <th>%Complete</th>    
  174.               <th>Forecast Date</th>    
  175.               <th>Actual Date</th>    
  176.               <th>Target Resolution Date</th>    
  177.               </tr>    
  178.               <a href="#" id="Addbutton" onClick={this.addClick.bind(this)}>+</a><br></br>    
  179.               {this.createUI()}    
  180.               </tbody>    
  181.           </table>    
  182.         </div>    
  183.         {this.mybutton()}      
  184.       </div>  </div>      
  185.     );    
  186.   }    
  187.   private AddProgram(): void{    
  188.         
  189.     let projectname = $("#ProjectName").val();    
  190.    
  191.     var AddData ={    
  192.       "ProgramName": projectname,    
  193.     };    
  194.     sp.web.lists.getByTitle("Program").items.add(AddData).then(i => {    
  195.       this.AddProject(i.data.Id);    
  196.     });    
  197.   }    
  198.   private UpdateProgram(): void {    
  199.     let projectname = $("#ProjectName").val();    
  200.     var UpdateData ={    
  201.       "ProgramName": projectname    
  202.     };    sp.web.lists.getByTitle("Program").items.getById(managerlistid).update(UpdateData).then(i => {    
  203.       this.updateproject();    
  204.     });    
  205.   }    
  206. }  
in ISpfxDynamicCOntrolsProps.ts
  1. import { WebPartContext } from '@microsoft/sp-webpart-base';      
  2. export interface ISpfxDynamicCOntrolsProps {    
  3.   description: string;    
  4.   context: WebPartContext;     
  5. }  
in ISpfxDynamicCOntrolsState.ts
  1. export interface ISpfxDynamicCOntrolsState {      
  2.     Projectstatus?:any[];    
  3. } 
Here  I am using 2 lists, namely Program and ProjectStatus.
 
Program list contains ProgramName field.
 
ProjectStatus list contains MileStone,PercentageComplete,ForcastDate,ActualDate,TargetResolutionDate fields.
 
Dynamic Fields are used in the second list.
 
Sample output
 
 
 
I hope this helps someone.