Search This Blog

Monday, February 28, 2022

Removing the Nesting object in to single object

 Iterating the array of objects and removing the nested object and adding in single object


Json Object:


  1. results[10]

    1. 0{

    2. hospital_details: { 

    3. site_id: "61624374", description: "ACCESS LH CALIBRATOR", name: "SOUL DIAGNOSTICS", 
    4. city: "BENGALURU"

    5. }

    6. end_customer_details : {

      1. site_id: "61624374", description: "ACCESS LH CALIBRATOR", name: "SOUL DIAGNOSTICS", 
      2. city: "BENGALURU"
    7. }

    8.   "toSalesOrder": "",
    9.   "toSalesOrderLineNumber": "", 
    10.   "toSalesOrderLineDetailedNumber": "",
    11.   "toInvoiceNumber": "",
      1. availableQuantity1
      2. cpNumber"3061392"
      3. created_on"2021-12-01T16:14:50.115995Z"


    12. }

  1. 1{

  2. hospital_details: { 

  3. site_id: "61624374", description: "ACCESS LH CALIBRATOR", name: "SOUL DIAGNOSTICS", 
  4. city: "BENGALURU"

  5. }

  6. end_customer_details : {

    1. site_id: "61624374", description: "ACCESS LH CALIBRATOR", name: "SOUL DIAGNOSTICS", 
    2. city: "BENGALURU"
  7. }

  8.   "toSalesOrder": "",
  9.   "toSalesOrderLineNumber": "", 
  10.   "toSalesOrderLineDetailedNumber": "",
  11.   "toInvoiceNumber": "",
    1. availableQuantity1
    2. cpNumber"3061392"
    3. created_on"2021-12-01T16:14:50.115995Z"

  12. }


Output:
  1. results[10]

    1. 0{
  1. end_customer_name"IGENETIC DIAGNOSTICS PVT LTD"
  2. end_customer_pincode"400072"
  3. end_customer_region"WEST"
  4. end_customer_site_id"46280291"
  5. end_customer_state"MAHARASHTRA"
  6. fromEndCustomerNumber"10195892"
  7. fromInvoiceNumber"17331148051"
  8. "toSalesOrder": "", "toSalesOrderLineNumber": "", "toSalesOrderLineDetailedNumber": "", "toInvoiceNumber": "", availableQuantity: 1 cpNumber: "3061392" created_on: "2021-12-01T16:14:50.115995Z"



}

 res['results'].forEach((element: any, index) => {

           let hospitaldetails = element.hospital_details;
           let customerdetails =   element.end_customer_details;
           let grid =  Object.assign(element, hospitaldetails, customerdetails);      
           this.gridData.push(grid);
        });    

Friday, February 4, 2022

Higher order functions

 Iterating the array of objects and changing the value of object


const products = [ { name: 'Laptop', price: 32000, brand: 'Lenovo', color: 'Silver' },
    { name: 'Phone', price: 700, brand: 'Iphone', color: 'Golden' },
    { name: 'Watch', price: 3000, brand: 'Casio', color: 'Yellow' },
    { name: 'Aunglass', price: 300, brand: 'Ribon', color: 'Blue' },
    { name: 'Camera', price: 9000, brand: 'Lenovo', color: 'Gray' },
];

var results = [];
for(let i = 0; i < products.length; i++)
{
    //console.log(products[i]);

    products[i].name = products[i].name.toUpperCase();

    results.push(products[i]);
   
}

Sunday, September 8, 2019

Learn Promise async await in Javascript

<!DOCTYPE html>
<html>
<body>

<p>This example uses the addEventListener() method to attach a click event to a button.</p>

<button id="myBtn">Try it</button>

<p><strong>Note:</strong> The addEventListener() method is not supported in Internet Explorer 8 and earlier versions.</p>

<p id="demo"></p>

<script>
window.addEventListener("load", function(){

});



function execute(a, b, c)
{
  result = a + b;
  console.log(result);
  //c(result);
}
execute(5, 6, function(data)
{
  console.log(data);
});

var promise = new Promise(function(resolve, reject)
{
  //setTimeout(function()
 // {
//     resolve("Success");
 // }, 2000);

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     
       resolve(xhttp.response);
    }
};
xhttp.open("GET", "https://5d74dc3dd5d3ea001425b027.mockapi.io/userss", true);
xhttp.send();
 
 
});

promise.then(function(data)
{
 console.log(JSON.parse(data));
}).catch(function(err)
{
 console.log(err);
});


//async function foo()
//{
 // return Promise.resolve(1);
// }
//foo().then(alert);


async function foo()
{
     let promise = new Promise(function (resolve, reject)
{
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
         resolve(xhttp.response);
         }
};
        xhttp.open("GET", "https://5d74dc3dd5d3ea001425b027.mockapi.io/userss", true);
        xhttp.send();


 });
  let result = await promise;
  alert(result);
 }
 foo();


 async function foos()
 {
   try {
        let response = await fetch("https://5d74dc3dd5d3ea001425b027.mockapi.io/userss");
let result = await response.json();

  } catch(e) {
    // catches errors both in fetch and response.json
    alert(e);
  }


   

 }
 foos();
</script>

</body>
</html>

Friday, September 6, 2019

creating a multi item carousel using bootstrap and sharepoint.

Step1:

Welcome to sharepoint discussion forum, so, Today we are going to discuss how to create a multi item carousel in step by step using bootstrap and sharepoint.

Step 2 : 

First of all, We need a carousel which runs in the bootstrap framework, instead of using third-party plugins to avoid conflict.  Below is the design which we have to implement in sharepoint




Step 3 :

We have to create a separate page to implement this carousel in sharepoint.  goto - All Files->_catalogs> masterpage > assets > html > rockstarsforthemonth.html.

Paste the below code with html markup and  Sharepoint Rest api call

Source Code :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <!-- This file has been downloaded from Bootsnipp.com. Enjoy! -->
    <title>Rockstars for the month</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">

<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">
 
    <style type="text/css">
        .MultiCarousel { float: left; overflow: hidden; padding: 0px; width:97.5%; position:relative;
        background-color: #ededed;}
    .MultiCarousel .MultiCarousel-inner { transition: 1s ease all; float: left; }
        .MultiCarousel .MultiCarousel-inner .item { float: left;}
        .MultiCarousel .MultiCarousel-inner .item > div { text-align: center; padding:30px; margin:6px 5px 5px 6px; background:#ffffff; color:#666;}
    .MultiCarousel .leftLst, .MultiCarousel .rightLst { position:absolute; border-radius:50%;top:calc(50% - 20px); }
    .MultiCarousel .leftLst { left:14px; }
    .MultiCarousel .rightLst { right:15px; }
    .MultiCarousel .leftLst.over, .MultiCarousel .rightLst.over { pointer-events: none; background:#8a8686;     border-color: #8a8686 }
        .btn-primary {
    color: #fff;
    background-color: #bd5355;
    border-color: #bd5355;
}
     
        .btn-primary:hover, .btn-primary:focus, .btn-primary.focus, .btn-primary:active, .btn-primary.active, .open>.dropdown-toggle.btn-primary {
    color: #fff;
     background-color: #bd5355;
    border-color: #bd5355;
}
        .MultiCarousel h4
        {
            margin-top: 17px;
            color:#aa2225 !important;
            font-size: 24px;
            margin-top: 30px;
            margin-bottom: 0px;
        }
       .MultiCarousel p
        {
            color:#2e2929;
            font-weight: bold;
            font-size:17px;
        }
     
        .MultiCarousel .btn:focus, .MultiCarousel .btn:active:focus, .MultiCarousel .btn.active:focus, .MultiCarousel .btn.focus, .MultiCarousel .btn:active.focus, .MultiCarousel .btn.active.focus {
           outline: none;
        }
        .MultiCarousel .img-circle
        {
            width:150px;
            height: 150px;
        }
        .MultiCarousel .btn {
           padding: 10px 12px 0px 10px;
        }
        .MultiCarousel .fa-chevron-right
        {
        padding-left:2px;


}
    </style>

</head>
<body>
<div class="container" style="margin-top:50px;">
<div class="row">
<div class="MultiCarousel" data-items="1,3,5,6" data-slide="1" id="MultiCarousel"  data-interval="1000">
            <div class="MultiCarousel-inner">
             
     
             
            </div>
            <div class="btn btn-primary leftLst"><i class="fa fa-chevron-left" aria-hidden="true"></i></div>
            <div class="btn btn-primary rightLst"><i class="fa fa-chevron-right" aria-hidden="true"></i></div>
        </div>
</div>

</div>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>

<script type="text/javascript">

$(document).ready(function () {

function retriveListItem()
{
 
    $.ajax
    ({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Rockstars')/items?$select=FileRef/FileRef,EmployeeName,EmployeeDepartment,IsActive&$filter=IsActive eq 1",
        type: "GET",
        headers:
        {
            "Accept": "application/json;odata=verbose",
       
        },
       
        success: function(data) 
        {
   
         $(".MultiCarousel-inner").empty();
            for (var i = 0; i < data.d.results.length; i++) 
            {
                var item = data.d.results[i];               
if(item.EmployeeName !=null && item.EmployeeDepartment !=null)
    {
                 var rockhtml ='<div class="item"><div class="image-flip" ontouchstart="this.classList.toggle("hover");">' +
                             '<div class="mainflip"> <div class="frontside"><div class="card"><div class="card-body text-center">' +
                             '<img class="img-circle" src="' + _spPageContextInfo.webAbsoluteUrl + item.FileRef + '">' +
                             '<h4 class="card-title">' + item.EmployeeName + '</h4> <p class="card-text">' + item.EmployeeDepartment + '</p></div></div></div></div></div></div>'


                  $(".MultiCarousel-inner").append(rockhtml);               
             
                }
                ResCarouselSize();
            }
        },
        error: function(data)
        {
       
            $(".MultiCarousel-inner").empty().text(data.responseJSON.error);
        }
    });
}



    var itemsMainDiv = ('.MultiCarousel');
    var itemsDiv = ('.MultiCarousel-inner');
    var itemWidth = "";

    $('.leftLst, .rightLst').click(function () {
        var condition = $(this).hasClass("leftLst");
        if (condition)
            click(0, this);
        else
            click(1, this)
    });

    ResCarouselSize();
    retriveListItem()
 
    $(window).resize(function () {
   
        ResCarouselSize();
    });

    //this function define the size of the items
    function ResCarouselSize() {
        var incno = 0;
        var dataItems = ("data-items");
        var itemClass = ('.item');
        var id = 0;
        var btnParentSb = '';
        var itemsSplit = '';
        var sampwidth = $(itemsMainDiv).width();
        var bodyWidth = $('body').width();
        $(itemsDiv).each(function () {
            id = id + 1;
            var itemNumbers = $(this).find(itemClass).length;
            btnParentSb = $(this).parent().attr(dataItems);
            itemsSplit = btnParentSb.split(',');
            $(this).parent().attr("id", "MultiCarousel" + id);


            if (bodyWidth >= 1200) {
                incno = itemsSplit[3];
                itemWidth = 284.9;
            }
            else if (bodyWidth >= 992) {
                incno = itemsSplit[2];
                itemWidth = 300;
            }
            else if (bodyWidth >= 768) {
                incno = itemsSplit[1];
                itemWidth = sampwidth / incno;
            }
            else {
                incno = itemsSplit[0];
                itemWidth = sampwidth / incno;
            }
            $(this).css({ 'transform': 'translateX(0px)', 'width': itemWidth * itemNumbers });
            $(this).find(itemClass).each(function () {
                $(this).outerWidth(itemWidth);
            });

            $(".leftLst").addClass("over");
            $(".rightLst").removeClass("over");

        });
         


    }


    //this function used to move the items
    function ResCarousel(e, el, s) {
        var leftBtn = ('.leftLst');
        var rightBtn = ('.rightLst');
        var translateXval = '';
        var divStyle = $(el + ' ' + itemsDiv).css('transform');
        var values = divStyle.match(/-?[\d\.]+/g);
        var xds = Math.abs(values[4]);
        if (e == 0) {
            translateXval = parseInt(xds) - parseInt(itemWidth * s);
            $(el + ' ' + rightBtn).removeClass("over");

            if (translateXval <= itemWidth / 2) {
                translateXval = 0;
                $(el + ' ' + leftBtn).addClass("over");
            }
        }
        else if (e == 1) {
            var itemsCondition = $(el).find(itemsDiv).width() - $(el).width();
            translateXval = parseInt(xds) + parseInt(itemWidth * s);
            $(el + ' ' + leftBtn).removeClass("over");

            if (translateXval >= itemsCondition - itemWidth / 2) {
                translateXval = itemsCondition;
                $(el + ' ' + rightBtn).addClass("over");
            }
        }
        $(el + ' ' + itemsDiv).css('transform', 'translateX(' + -translateXval + 'px)');
    }

    //It is used to get some elements from btn
    function click(ell, ee) {
        var Parent = "#" + $(ee).parent().attr("id");
        var slide = $(Parent).attr("data-slide");
              ResCarousel(ell, Parent, slide);
    }

});
    </script>


 Step 5 :

Enjoy Folks

Thursday, August 29, 2019

How integrate angular model driven form in Sharepoint framework

Step1:

Welcome to model driven form,We need to import the ReactiveFormsModule from @angular/forms and use the same in the imports array. app.module.ts

Step2:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './Components/app.component';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [ BrowserModule, HttpClientModule, FormsModule, ReactiveFormsModule],
declarations: [ AppComponent ],
providers: [ ],
bootstrap: [ AppComponent ] ,
})
export class AppModule {}


Step3:

Angular Form Design


<form (ngSubmit)="onSubmit(regForm)" [formGroup]="regForm">
<div class="borderbtm">
<div class="row">
<div class="col-md-6 box-body">
<div class="form-group">
<div class="col-md-12">
<label> Start Date</label>
</div>
<div class="col-md-12">
<div class="input-group date datetimepicker">
<input type="text" formControlName="startdate" name="startdate" class="form-control"/>
<span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div>
</div>
</div>
</div>
<div class="col-md-6 box-body">
<div class="form-group">
<div class="col-md-12">
<label> End Date</label>
</div>
<div class="col-md-12">
<div class="input-group date datetimepicker">
<input type="text" formControlName="enddate" name="enddate" class="form-control" />
<span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div>
</div>
</div>
</div>
</div>
</div>
<div class="box-footer" style="text-align:center; padding-top: 20px;">
<button class="btn btn-default clear" style="padding-right: 20px;" type="cancel">CLEAR</button>
<button class="btn btn-primary" type="submit">SUBMIT</button>
</div>
</form>


step 4

App.component.ts design below

import { Component, Input, OnInit, Inject, ViewEncapsulation } from '@angular/core';
import {IWebPartContext} from '@microsoft/sp-webpart-base';
import { SPHttpClient, SPHttpClientResponse, ISPHttpClientOptions } from '@microsoft/sp-http';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

export interface ISPLists {
value: ISPList[];
}
export interface ISPList {
Title: string;
Id: string;
}
@Component({
moduleId: module.id, // this is the key
selector: 'my-spfx-app',
template: require("./app.component.html") as string
//templateUrl: './app.component.html'
//styleUrls : ['./app.component.css']
// styleUrls : ['./app.component.css']

//styles: ['./app.component.css']
})


export class AppComponent implements OnInit {

public name: string = '';
public context:IWebPartContext;
showGrid = true;
employeeitems :any;
regForm:FormGroup;
employeeleaveitems;

constructor(private formbuilder: FormBuilder){ }
public ngOnInit() {
this.setFormState();
this.getleavelist();
}
setFormState():void
{
this.regForm = this.formbuilder.group({
startdate : ['',[Validators.required]],
enddate : ['',[Validators.required]]
});
}
getleavelist()
{
this.context= window["webPartContext"];
this.name= this.context.pageContext.user.displayName;
this._getListData()
.then((response) => {
console.log(response);
this._renderList(response.value);
console.log(response.value);
});
}

onSubmit()
{
debugger;
let leaves = this.regForm.value;
console.log(leaves);
this.leavepost(leaves);
}

addleaves()
{
this.showGrid = false;
}

private _getListData(): Promise<ISPLists> {
debugger;
return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + "/_api/web/lists/GetByTitle('SpfxLeave')/items", SPHttpClient.configurations.v1)
.then((response: SPHttpClientResponse) => {
debugger;
console.log(response);
return response.json();
});
}

private _renderList(items: ISPList[]): void {
this.employeeleaveitems =items;
}

leavepost(leaves:any) {



var itemType = "SP.Data.SpfxLeaveListItem";
var absoluteUri = this.context.pageContext.web.absoluteUrl;
const itemData: any = {
"__metadata": { "type": itemType },
'startdate':leaves.startdate,
'enddate': leaves.enddate,
'name': 'tentant name',
'leavetype': 'sick leave'
};
const itemHeader: any = {
'Accept': 'application/json;odata=nometadata',
'Content-type': 'application/json;odata=verbose',
'odata-version': '',
"X-HTTP-Method": "POST"
};
const spHttpClientOptions: ISPHttpClientOptions = {
"headers": itemHeader,
"body": JSON.stringify(itemData)
};
this.context.spHttpClient.post(
absoluteUri + "/_api/web/lists/GetByTitle('SpfxLeave')/items",
SPHttpClient.configurations.v1,
spHttpClientOptions);

}
}


step5:

Here's my tsconfig.json :

Add the below line without fail.

"emitDecoratorMetadata": true,

Enjoy Folks

Wednesday, June 19, 2019

How to remove special characters and codes (using jQuery) from SharePoint rendered html?

Welcome to designers dairy, Here we are going to discuss,How to remove special characters and codes (using jQuery) from SharePoint rendered html
Step1:
It is a big headache, when you render the html  in share-point, There are lot of special characters especially  char code "#8203".
Step2:
To remove this special code include in html while rendering the page, we have to write a jquery script 

Script:
    $(document).ready(function()
{
jQuery('.OnboardingOnlinePortal-wrapper').each(function(index,element)  { 

       var exp = new RegExp(String.fromCharCode(8203),"g");
       var editor= jQuery(element);
       var txt = editor.html()
           txt = txt.replace(exp,'');
           txt = txt.replace(/&nbsp;/g,' ')
           txt = txt.replace(/ {2,}/g,' ');
       editor.html(txt);
  });
  return true;
 });

Step3:
In my scenario, I have included this script in the Page layout, based on your requirements, you can add in Pages or master pages.
To add the script in Page layout below is the placeholder 
  <script>//<![CDATA[
    $(document).ready(function()
{
jQuery('.OnboardingOnlinePortal-wrapper').each(function(index,element)  {

       var exp = new RegExp(String.fromCharCode(8203),"g");
       var editor= jQuery(element);
       var txt = editor.html()
           txt = txt.replace(exp,'');
           txt = txt.replace(/&nbsp;/g,' ')
           txt = txt.replace(/ {2,}/g,' ');
       editor.html(txt);
  });
  return true;
 });

//]]>
 </script>
Step3:

Thanks for reading the article.Stay Tuned on www.webdesignersdairy.com  for more updates on SharePoint.

Validating to select in sequencial order using angular

    < input type = "checkbox" (change) = "handleSelectTaskItem($event, taskItem)" [checked] = " taskItem . i...