Tuesday, 18 August 2015

Hide the SharePoint Team site Page Ribbon and Quick Launch using css in SharePoint 2013

Put the below code snippet in the "PlaceHolderAdditionalPageHead" content place holder.


<SharePoint:StyleBlock runat="server">
body #s4-leftpanel {
display:none;
}
.s4-ca {
margin-left:0px;
}

.ms-core-listMenu-verticalBox,#s4-ribbonrow {display:none;}
#s4-titlerow {display:none!important;}
.ms-webpartPage-root {
&nbsp;&nbsp;&nbsp;&nbsp; border-spacing: 0px
!important;
}
.ms-webpartzone-cell {
margin: 0px !important;
&nbsp;}
#suiteBar{display:none;}
</SharePoint:StyleBlock>

Friday, 14 August 2015

ECMAScript Crud operation in SharePoint 2013




$(document).ready( function(){

$("#btnSave").click(function(){ AddListItem();} );


$("#btnUpdate").click(function(){ UpdateListItem();} );


$("#btnDelete").click(function(){

alert('Delete button is clicked ...!!!!');
DeleteListItem1();} );
}

);







function AddListItem(){
alert('AddListItem called ..!!');

    var ListName = "TestList";
    var context = new SP.ClientContext.get_current(); // the current context is taken by default here
    //you can also create a particular site context as follows
    //var context = new SP.ClientContext('/Sites/site1');
    var lstObject = context.get_web().get_lists().getByTitle(ListName);
    var listItemCreationInfo = new SP.ListItemCreationInformation();
    var newItem = lstObject.addItem(listItemCreationInfo);
    newItem.set_item('Title', 'This is new item');
    // set values to other columns of the list here
    newItem.update();
   
    alert('Hi...');
   
//context.executeQueryAsync(Function.createDelegate(this, this.onAddSuccess),Function.createDelegate(this, this.onAddFailure));

context.executeQueryAsync( function onAddSuccess() { alert('Item created: ' + newItem.get_id());} , Function.createDelegate(this, this.onAddFailure));


   
 }
     function onAddSuccess() { alert('Item created: ' + newItem.get_id());}

    function onAddFailure(sender, args) {

        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }











function UpdateListItem()
{
var ListName = "TestList";
var context = new SP.ClientContext.get_current(); // the current context is taken by default here
//you can also create a particular site context as follows
//var context = new SP.ClientContext('/Sites/site1');

var lstObject = context.get_web().get_lists().getByTitle(ListName);
this.lstObjectItem = lstObject.getItemById(75);
lstObjectItem.set_item('Title', 'This is updated item');
lstObjectItem.update();
lstObject.set_description("Updated description using ECMAScript");
lstObject.update();
context.executeQueryAsync(Function.createDelegate(this, this.onUpdateSuccess),
Function.createDelegate(this, this.onUpdateFailure));
}

function onUpdateSuccess() {
alert('Item udated');
}

function onUpdateFailure(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}







function DeleteListItem1()
{
alert('Delete function is callaed ...!!');

var ListName = "TestList";
var context = new SP.ClientContext.get_current(); // the current context is taken by default here
//you can also create a particular site context as follows
//var context = new SP.ClientContext('/Sites/site1');

var lstObject = context.get_web().get_lists().getByTitle(ListName);
this.lstObjectItem = lstObject.getItemById(75);
lstObjectItem.deleteObject();

context.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
Function.createDelegate(this, this.onFailure));
}

function onSuccess() {
alert('Item Deleted');
}

function onFailure(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

CRUD Operation with REST API in SharePoint 2013

Here , for example we take a custom List named 'TestList' with two columns .
(1) Title
(2) Designation

Below is the js file code snipped which have the CRUD operation functions.




// handle the click event of the button

$(document).ready( function(){


$("#btnSubmit").click(function(){

//alert ("Site" + _spPageContextInfo.siteAbsoluteUrl  );

//alert( "Web" +   _spPageContextInfo.webAbsoluteUrl );

CreateNew();

}  );


// Upadte Button


$("#btnUpdate").click( function() {

Update();

});



$("#btnDelete").click( function(){

deleteItem(54);
}
);



});



//===============   Start Create Item ============================================ //



// occurs when a user clicks the create button
function CreateNew() {
    var listName = "TestList";
    var newItemTitle = "New Title Item";
    CreateListItemWithDetails(listName, newItemTitle) ;
}

// CREATE Operation
// listName: The name of the list you want to get items from
// weburl: The url of the web that the list is in.
// newItemTitle: New Item title.
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails
function CreateListItemWithDetails(listName, newItemTitle) {
    var itemType = GetItemTypeForListName(listName);
    var item = {
        "__metadata": { "type": itemType },
        "Title": newItemTitle,
        "Designation" : 'Project Manager'
       
    };

 alert(JSON.stringify(item));


    $.ajax({
        url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
             success();
           
            //alert('success');
        },
        error: function (data) {
            failure();
         
           //alert('Error');
        }
    });
}

// Get List Item Type metadata
function GetItemTypeForListName(name) {
    return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}



//function success() { alert("New Item has been created successfully."); } // getListItems("TestList");}


function failure() {
     alert("Ooops, an error occured. Please try again.");
 }



//===============   End Create Item ============================================ //





// ============================================== Start Update Item  =================================================== //



// occurs when a user clicks the update button
function Update() {
    var listName = "TestList";
    var url = _spPageContextInfo.webAbsoluteUrl;
    var itemId = "55"; // Update Item Id here
    var title = "New Updated Title";
    updateListItem(itemId, listName, url, title, function () {
        alert("Item updated, refreshing avilable items");
    }, function () {
        alert("Ooops, an error occured. Please try again");
    });
}

// Update Operation
// listName: The name of the list you want to get items from
// siteurl: The url of the site that the list is in. // title: The value of the title field for the new item
// itemId: the id of the item to update
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails
function updateListItem(itemId, listName, siteUrl, title, success, failure) {


//alert('In UpdatelistItem');

    var itemType = GetItemTypeForListName(listName);

    var item = {
        "__metadata": { "type": itemType },
        "Title": title
    };

    getListItemWithId(itemId, listName, siteUrl, function (data) {
   
    alert('Update success function is called ..!!!'+ data.__metadata.uri );
   
    alert("Etag is  : " + data.d.__metadata.etag );
   
        $.ajax({
            url: data.__metadata.uri,
            type: "POST",
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(item),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "X-HTTP-Method": "MERGE",
                "If-Match": data.d.__metadata.etag
               // "If-Match": "*"
            },
            success: function (data) {
               // success(data);
               
                alert ('success');
               
            },
            error: function (data) {
                //failure(data);
               
                alert ('error');
            }
        });
    }, function (data) {
        failure(data);
    });
}


function getListItemWithId(itemId, listName, siteurl, success, failure) {

//alert('In GetListItemWithId');


    var url = siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items?$filter=Id eq " + itemId;
   // alert(url);
   
    $.ajax({
        url: url,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            if (data.d.results.length == 1) {
             
// alert('Item is fetched ..!!!'+ JSON.stringify(data.d.results[0]) );              
  success(data.d.results[0]);              
             
            }
            else {
               // failure("Multiple results obtained for the specified Id value");
            }
        },
        error: function (data) {
            //failure(data);
           
            alert('Item not found ...!!!');
           
        }
    });
}




// ============================================== End Update Item  =================================================== //







// ============================= Start Delete Item ================================================================= //




function deleteItem(id) {
alert('Delete Function is called ..!!!');

var DeleteItemUrl = "/_api/Web/Lists/GetByTitle('TestList')/getItemById('"+id+"')";
    $.ajax({      
        url: _spPageContextInfo.webAbsoluteUrl + DeleteItemUrl,
        type: "POST",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "If-Match": "*",
            "X-Http-Method": "DELETE"
        },
        success: function (data) {
           alert('Delete Successfully ..!!!');
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });
}












// ============================= End Delete Item ================================================================= //


function getListItems(listname ) {
// Getting our list items
$.ajax({
//url: url + "/_api/web/lists/getbytitle('" + listname + "')/items(" + id + ")",
//url: url + "/_api/web/lists/getbytitle('" + listname + "')/Items",
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listname + "')/Items",

method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
// Returning the results
 
  var items = data.d.results;
 
  var html = "<table>";
 
  for (var i = 0; i < items.length; i++)
  {          
//alert(items[i].Id+ " : " + items[i].Title);      

html = html + "<tr> <td>"+items[i].Id+"</td> <td>"+items[i].Title+"</td> </tr>";

}

html = html+ "</table>" ;

//$("#resultarea").append(html);



$("#resultarea").html(html);



},
error: function (data) {
alert('In Error..'+JSON.stringify(data)); }
});
};


function complete(data) {
alert("Completed successfully."  );



var jsonObject = JSON.parse(data.body);

alert(jsonObject );

var results = jsonObject.d.results;

for (var i = 0; i < results.length; i++) {

           alert('In for loop ..!!!' +  results[i].Title);

        }


}
function failure(data) {
alert("Operation failed.");
}

Thursday, 13 August 2015

HTML Table Export To Excel _ In SharePoint Using Custom WebPart

I had some requirement that I want to export my html table to Excel sheet. So, I used to below some line of code for that.

public void ExportExcel()
        {
            Response.AppendHeader("content-disposition", "attachment;filename=ExportedHtml.xls");
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/vnd.ms-excel";
            this.EnableViewState = false;
            Response.Write(ExportDiv);
            Response.End();

        }

But, Here I got some problem. After downloading the excel sheet by browser, the Page was unresponsive i.e. no postback was there after the file downloaded. That was very strange for me, because the same code was working with the normal asp.net page and not with the SharePoint Page.
But thanks to Google and StackOverflow, that I got some link with the excect issue and solution.

Actually, when we download the excel file using the http, at that time for SharePoint Page , there is one property named _spFormOnSubmitCalled becomes true , which is by default false.
We will set it to the false again and the postback will work for us.

The detailed information you will get from the below link :
http://stackoverflow.com/questions/2336883/post-back-does-not-work-after-writing-files-to-response-in-asp-net



Here, when we download the Excel file, we got the warning for the formate of the excel sheet , we need to use another way to solve it.

We need to use below code for that : 

Hope, this blog will help you.

Thanks.


Wednesday, 12 August 2015

Disable List Form Feilds Using Jquery in SharePoint

<!--Start Additional Custom Code -->

<script type="text/javascript" src="../../SiteAssets/jquery-1.11.3.min.js"></script>

<script type="text/javascript">

$(document).ready(function(){




$("input[Title='Title']").attr('disabled', 'disabled');    // To set the Title Feild Disable



alert( $("Select[Title='ServiceStage'] option:selected").text());  // To get the  dropdown ServiceStage Selected Value


$("textarea[Title='Title']").attr('disabled', 'disabled');  // To Disable the Multiline Feild




});
</script>




<!--End Additional Custom Code -->

Tuesday, 30 June 2015

SharePoint Designer Workflow : Set the Custom List Field using LookUp Feild in SPD Workflow

Here, we need to set the Custom list Feild using Lookup item Value.

For that we used Sharepoint Workflow 2010 version and as we got some error to getting the Lookup value as a Text in the SharePoint Workflow 2013.

The Workflow is as below, this is the final workflow :





To set the  lookup item , we need to set the values as below.


And to set the Find the list Item section, we need to set the value as below  :


Then, we need to save and publish the workflow.
And also need to do some settings when we need to fire the workflow as per our requirement.


Filter the Lookup feild data based on some condition

We may have some requirement that we do not want to show all data of the lookup to every one.

I have some scenario as below :

I have the Master custom list named OfficeMaster and I use the lookup using this in Child list 'FacilityStatus'.

OfficeMaster Custom also had one more column named OfficeAdmin , which have the office Admin name, who can add data for this office.

In that, I just want to show that Office To admin , which office is assigned to him in the OfficeMaster List.

For that, I used the SPServices named "SPFilterDropdown()".

So, when Office Admin Login into the site, he can only see that offices whom Admin he is.

$().SPServices.SPFilterDropdown({
                                                  relationshipList: "OfficeMaster",
                                                  relationshipListColumn: "OfficeLocation",
                                                  columnName: "OfficeName",                                                                                                
                                                                                             
                                                  CAMLQuery: "<Eq><FieldRef Name='OfficeAdmin' /><Value Type='User'>"+username+"</Value></Eq>",
                                                  completefunc: null,
                                                  debug: true
                                                });
 
 


Here , username parameter is used which uses the users username. I am using the ECMA script for that and put that code above that.

this.context= SP.ClientContext.get_current();
            if (this.context!= undefined && context!= null) {

//assume we have a client context called context.
var web = context.get_web();
var user = web.get_currentUser(); //must load this to access info.
context.load(user);
//alert('start In Middle');
context.executeQueryAsync(function(){
  // alert("User is: " + user.get_title()); //there is also id, email, so this is pretty useful.
   
   username=user.get_title();
}, function(){alert(":(");});
}