Search This Blog

Showing posts with label SPFX. Show all posts
Showing posts with label SPFX. Show all posts

Monday, November 16, 2020

Global variable undefined inside function - SPfx

Arrow functionsthings are special/differentArrow Functions always lexically bind the context (Lexical Scoping means that it uses this from the code that contains the Arrow Function.) and therefore this will refer to the originating context, ie the class.


  A simpler example might make it more clear.
  
  const obj = {
    myVar: 'foo',
    myFunc: function() { 
      console.log('Actual Variable value: ',this.myVar)  
  
      setTimeout(() => {
        console.log('Set timeout using Arrow function: ',this.myVar)
      }, 1000);
      setTimeout(function () {
        console.log('Set timeout using Normal function: ',this.myVar)
      }, 1000);
    }
  }
  obj.myFunc();
  Output
  
  Actual Variable valuefoo
  Set timeout using Arrow function:  foo
  Set timeout using Normal function:  undefined

Sunday, November 15, 2020

SPFx - insertBulkItem

private insertBulkItem(elementsany[]): Promise<any> {
  return new Promise((resolvereject=> {

    if (elements.length > 0) {
      // get first element of the array
      const element = elements[0];
      // remove the first element of the array
      elements.shift();
      pnp.sp.web.lists.getByTitle('Test').items.add(element).then(response => {
        console.log('then...'response);
        // call function again (first element removed before)
        return this.insertBulkItem(elements);
      }).catch(error => {
        console.log('catch...'error);
        reject(error);
      });
    } else {
      // no (more) items in array
      resolve(null);
    }

  });

} 

 // elements to add
    // with EXACTLY the columns to set in SharePoint
    const elements = [
      {
        Title: 'el1',
      },
      {
        Title: 'el2',
      },
      {
        Title: 'el3',
      },
    ];

    // add all the elements ordered
    this.insertBulkItem(elements).then(response => {
      // all added correctly
      // do some stuff ...
      console.log('success');
    }).catch(error => {
      // some error happened at some point...
      // handle the error ...
      console.log('something went wrong');
    });


option with async and await
// call function
this.insertBulkItem(elements);

// async function with await
private async insertBulkItem(elements: any[]) {
  for (const element of elements) {
    await pnp.sp.web.lists.getByTitle('Test').items.add(element);
  }
}

Wednesday, November 11, 2020

SPFx get current url and current user and load master data

     pnp.sp.site.getWebUrlFromPageUrl(window.location.href)

      .then(res => {
        this.absoluteUrl = res;
        pnp.sp.web.currentUser.get().then(result => {
          this.CurntUserId = result.Id;
          this.CurntUserEmail = result.Email;
          this.CurntUserTitle = result.Title;
          this.SubmittedBy = result.Title;
          //inital querter
          this.MonthTitle = this.getQuarter(new Date()).toString();
          this.MonthNumber = this.getQuarter(new Date()).toString();
          //bind master data
          this.LoadAllMasterData();
          var queryReqId = new UrlQueryParameterCollection(window.location.href);
          if (queryReqId != null && queryReqId != undefined) {
            if (queryReqId.getValue("ReqId") != undefined) {
              this.loadDataLS(queryReqId.getValue("ReqId"));
            }
            else {
              this.getUniqueNumber();
            }
          }

        });
      });

Thursday, October 1, 2020

SPFx -AngularJs

 import {SalesLetterDataService,IList,ISLTypeMonthMaster,ISLCategoryMasterfrom './SalesLetterService'//class name(interface) mentioned here

export class SalesLetterController {
  public isLoadingboolean = false;
  public newItemstring = null;
  public userNamestring = "";
  public userJobTitlestring = "";
  public webSiteTitlestring = "";
  public welComeMessagestring = "";
  public userImageUrlstring = "";
  public greetingMessagestring = "";
  public prefixWelcomeMessagestring = "Welcome to ";  

  //vairble
  public SalesLetterTypestring = "";
  public SalesLetterTypeYearstring = "";
  public SalesLetterTypeMonthstring = "4";;   
  public SLTypeMaster:string="SLTypeMaster";
  public SLTypeMonthMaster:string="SLTypeMonthMaster";
  public SLTypeYearMaster:string="SLTypeYearMaster";
  public SLCategoryMaster:string="SLCategoryMaster";
  public SLTypeMasterListCollectionIList[] = [];  
  public SLTypeMonthMasterListCollectionISLTypeMonthMaster[] = []; 
  public SLTypeYearMasterListCollectionIList[] = []; 
  public SLCategoryMasterListCollectionISLCategoryMaster[] = []; 

   //NAInitiativeInfo
   public CheckboxNAInitiativeInfo = [];
   public SelectionCheckboxInformation = [];

  public static $injectstring[] = ['salesLetterDataService''$window',"$scope"]; //import name based on app-mondule 
  constructor(private dataServiceSalesLetterDataServiceprivate $windowangular.IWindowServiceprivate $scopeng.IScope) {
       // tslint:disable-next-line: no-shadowed-variable 
       this.LoadAllMasterData();
  }
  private LoadAllMasterData(): void {
    this.isLoading = true;
   
    this.dataService.getListItems(this.SLTypeMaster,"/sites/dev/") .then((itemIList[]): void => {
        this.SLTypeMasterListCollection = item;
      })
      .finally((): void => {
        this.isLoading = false;
      });
      this.dataService.getListItems(this.SLTypeYearMaster,"/sites/dev/") .then((mIList[]): void => {
        this.SLTypeYearMasterListCollection = m;
      })
      .finally((): void => {
        this.isLoading = false;
      });
      this.dataService.getMonthListItems(this.SLTypeMonthMaster,"/sites/dev/") .then((mItemISLTypeMonthMaster[]): void => {
        this.SLTypeMonthMasterListCollection = mItem;
        var inumber = 0;
        mItem.forEach(prd => {         
        if(mItem[i].QType=="1"){

        }          
          i++;
        });
      })
      .finally((): void => {
        this.isLoading = false;
      });
      this.dataService.getCategoryListItems(this.SLCategoryMaster,"/sites/dev/") .then((qItemISLCategoryMaster[]): void => {
        this.SLCategoryMasterListCollection = qItem;       
      })
      .finally((): void => {
        this.isLoading = false;
      });
    
  } 
  public getValues = () => {   
    if (new Date().getHours() > 0 && new Date().getHours() < 12this.greetingMessage = "Good Morning ";
    else if (new Date().getHours() >= 12 && new Date().getHours() <= 5this.greetingMessage = "Good Afternoon ";
    else if (new Date().getHours() > 5this.greetingMessage = "Good Evening ";
    if (this.userName.length == 0this.userName = "Jaisaravanan !";
    if (this.userJobTitle.length == 0this.userJobTitle = "";
    if (this.webSiteTitle.length == 0this.webSiteTitle = this.prefixWelcomeMessage + "Demo of SPFx Web Part";
    if (this.welComeMessage.length == 0this.welComeMessage = this.greetingMessage + this.userName;
    // if (this.userImageUrl.length == 0)  
    // this.userImageUrl ="";  
    this.getUserInformation();
  }
  public getUserInformation = () => {
    this.dataService.getCurrentUserInformation().then(ig => {
      this.webSiteTitle = this.prefixWelcomeMessage + this.webSiteTitle;
      this.userImageUrl = ig.userImageUrl;
      //this.userName = this.userName;  
      this.userJobTitle = ig.userJobTitle;
      //this.$scope.$apply();
    });
  } 
}
export let SalesLetterComponent = {
  selector: "salesLetterComponent"//based on className and must be small case in first letter
  template: require("./CreateSalesLetter.html").toString(),
  bindings: {},
  controller: SalesLetterController 
};

--------------------------------------------------


import * as angular from 'angular';
import * as $pnp from "sp-pnp-js";
import { SPListOperations } from 'spfxhelper';
export interface ILoginUserProp {
  userImageUrlstring;
  userJobTitlestring;
  userNamestring;
  webSiteTitlestring
}
export interface IListItem {
  Idstring;
  Titlestring;
  ModifiedDate;
  CreatedDate;
  Modifiedbystring;
  Createdbystring;
}
export interface IList {
  Idstring;
  Titlestring;
  ModifiedDate;
  CreatedDate;
}
export interface IList {
  Idstring;
  Titlestring;
  ModifiedDate;
  CreatedDate;
}
export interface ISLTypeMonthMaster extends IList {
  QTypestring;
}
export interface ISLTypeMonthMasterListItem extends IListItem {
  QTypestring;
}
export interface ISLCategoryMaster extends IList {
  CategoryCodestring;
}
export interface ISLCategoryMasterListItem extends IListItem {
  CategoryCodestring;
}
export class SalesLetterDataService {
  public static $injectstring[] = ['$q''$http'];
  constructor(private $qangular.IQServiceprivate $httpangular.IHttpService) { }
  public getListItems(listNamestringabsoluteUrlstring): angular.IPromise<IList[]> {
    const deferredangular.IDeferred<IList[]> = this.$q.defer();
    let urlstring = absoluteUrl + `/_api/web/lists/getbytitle('${listName}')/items?$select=* &$orderby=Modified desc`;
    this.$http({
      url: url,
      method: 'GET',
      headers: {
        'Accept': 'application/json;odata=nometadata'
      }
    }).then((resultangular.IHttpPromiseCallbackArg<{ valueIListItem[] }>): void => {
      const infoIList[] = [];
      for (let inumber = 0i < result.data.value.lengthi++) {
        const pIListItem = result.data.value[i];
        info.push({
          Id: p.Id,
          Title: p.Title,
          Modified: p.Modified,
          Created: p.Created
        });
      }
      deferred.resolve(info);
    });
    return deferred.promise;
  }
  public getMonthListItems(listNamestringabsoluteUrlstring): angular.IPromise<ISLTypeMonthMaster[]> {
    const deferredangular.IDeferred<ISLTypeMonthMaster[]> = this.$q.defer();
    let urlstring = absoluteUrl + `/_api/web/lists/getbytitle('${listName}')/items?$select=* &$orderby=Modified desc`;
    this.$http({
      url: url,
      method: 'GET',
      headers: {
        'Accept': 'application/json;odata=nometadata'
      }
    }).then((resultangular.IHttpPromiseCallbackArg<{ valueISLTypeMonthMasterListItem[] }>): void => {
      const infoISLTypeMonthMaster[] = [];
      for (let inumber = 0i < result.data.value.lengthi++) {
        const qISLTypeMonthMasterListItem = result.data.value[i];
        info.push({
          Id: q.Id,
          Title: q.Title,
          QType: q.QType,
          Modified: q.Modified,
          Created: q.Created
        });
      }
      deferred.resolve(info);
    });
    return deferred.promise;
  }
  public getCategoryListItems(listNamestringabsoluteUrlstring): angular.IPromise<ISLCategoryMaster[]> {
    const deferredangular.IDeferred<ISLCategoryMaster[]> = this.$q.defer();
    let urlstring = absoluteUrl + `/_api/web/lists/getbytitle('${listName}')/items?$select=* &$orderby=Modified desc`;
    this.$http({
      url: url,
      method: 'GET',
      headers: {
        'Accept': 'application/json;odata=nometadata'
      }
    }).then((resultangular.IHttpPromiseCallbackArg<{ valueISLCategoryMasterListItem[] }>): void => {
      const infoISLCategoryMaster[] = [];
      for (let inumber = 0i < result.data.value.lengthi++) {
        const qISLCategoryMasterListItem = result.data.value[i];
        info.push({
          Id: q.Id,
          Title: q.Title,
          CategoryCode: q.CategoryCode,
          Modified: q.Modified,
          Created: q.Created
        });
      }
      deferred.resolve(info);
    });
    return deferred.promise;
  }
  public getCurrentUserInformation = (): Promise<ILoginUserProp=> {
    let promise = new Promise<ILoginUserProp>((resolvereject=> {
      let igILoginUserProp = {
        userImageUrl: "",
        userJobTitle: "",
        userName: "",
        webSiteTitle: ""
      };
      $pnp.sp.profiles.myProperties.get().then(data => {
        data.UserProfileProperties.forEach(property => {
          if (property.Key == "Title") {
            ig.userJobTitle = property.Value;
          }
          if (property.Key == "PictureURL") {
            if (property.Value !== '') {
              ig.userImageUrl = property.Value;
            } else {
              ig.userImageUrl = "#";
            }
            ig.userImageUrl = ig.userImageUrl.replace("MThumb""LThumb");
          }
        });
        resolve(ig);
      }, error => {
        reject(error);
      });
    });
    return promise;
  }
}

---------------------------------------------
 <div class="row" data-ng-controller="salesLetterController as ctrl">
       <div class="col-md-6  pt-1">
          <select name="ddlSLTypeMaster" id="ddlSLTypeMaster" class="form-control form-control-sm" ng-model="ctrl.SalesLetterType" required>
                          <option ng-repeat="item in ctrl.SLTypeMasterListCollection" ng-selected="ctrl.SalesLetterType == item.Title" value="{{item.Title}}">{{item.Title}}</option>
                            <option value="">--Select--</option>
          </select>
                                                              </div>
   <div class="col-md-3  pt-1">
            <select name="ddlSLTypeMonth" id="ddlSLTypeMonth" class="form-control form-control-sm" ng-change="getSLMonthType()" ng-model="ctrl.SalesLetterTypeMonth" required>
                    <option ng-repeat="item in ctrl.SLTypeMonthMasterListCollection" ng-selected="ctrl.SalesLetterTypeMonth == item.QType" value="{{item.QType}}">{{item.Title}}</option>
                         <option value="">--Select--</option>
          </select>
        </div>
    <div class="col-md-3  pt-1">
            <select name="ddlSLTypeYear" id="ddlSLTypeYear" class="form-control form-control-sm" ng-change="getSLMonthType()" ng-model="ctrl.SalesLetterTypeYear " required>
                   <option ng-repeat="item in ctrl.SLTypeYearMasterListCollection" ng-selected="ctrl.SalesLetterTypeYear == item.Title" value="{{item.Title}}">{{item.Title}}</option>
                       <option value="">--Select--</option>
                         </select>
             </div>
  </div>