Tuesday, 4 December 2018

How to redirect the current user to the existing item from the new-item page?


Add the following to a web-part on the new-item page:

<script type="text/javascript" language="javascript">
var masterDataList;

ExecuteOrDelayUntilScriptLoaded(getWebUserData, "sp.js");

function getWebUserData() {

clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
currentUser = web.get_currentUser();
currentUser.retrieve();
clientContext.load(web);
clientContext.executeQueryAsync(onSuccessMethodGetUser, onFailureGetUser);
}

function onSuccessMethodGetUser(sender, args) {
var userObject = web.get_currentUser();
var userName = userObject.get_title(); //get_email();
masterDataList= web.get_lists().getByTitle('List Name');
var camlQuery = new SP.CamlQuery();
var query = "<View><Query><Where><Contains><FieldRef Name='Resource_x0020_Email' /><Value Type='Text'>" + userName + "</Value></Contains></Where></Query></View>";
camlQuery.set_viewXml(query);
masterDataListItem= masterDataList.getItems(camlQuery);
clientContext.load(masterDataListItem);
clientContext.executeQueryAsync(onMasterDataListItemsLoadSucceeded,onMasterDataListItemsLoadFailed);
}

function onFailureGetUser(sender, args)
{
//Do nothing
}

function onMasterDataListItemsLoadSucceeded(sender,args)
{
var itemID;
var itemsEnumerator=masterDataListItem.getEnumerator();
//Fetch latest item
while(itemsEnumerator.moveNext())
{
var currentItem=itemsEnumerator.get_current();
itemID=currentItem.get_item('ID');
}
if(itemID!=undefined)
{
window.location.href="https://server/sites/site_name/Lists/list_name/Item/editifs.aspx?ID="+itemID+"";
}
}

function onMasterDataListItemsLoadFailed(sender,args)
{
//Do nothing
}

</script>

Friday, 16 November 2018

SharePoint Excel Service : How to resolve "the workbook cannot be opened" error?


Run following commands for each web application that is associated with Excel Services:

$w = Get-SPWebApplication -identity http://<WebApplication>
$w.GrantAccessToProcessIdentity("<Domain>\<Username>")


In future, for the additional content databases, you must rerun these cmdlets to ensure that Excel Services has access to the new databases.


Source: https://docs.microsoft.com/en-us/sharepoint/administration/configure-excel-services

Thursday, 15 November 2018

SharePoint Application Page: How to export Gridview data to Excel file using ActiveX?


Note: This feature works only in IE. Also, you would need to enable ActiveX in IE settings and add the URL in trusted sites.

Prerequisite 1: IE Settings -> Internet Options -> Security -> Trusted Sites -> Custom Levels -> ActiveX Settings -> Enable/Prompt for ActiveX not marked as safe.

Prerequisite 2: IE Settings -> Internet Options -> Security -> Trusted Sites -> Add URL


Javascript:

<script language="javascript" type="text/javascript">
function exportTable() {
var x = document.getElementById('table_id').rows;
var xls = new ActiveXObject("Excel.Application");
xls.visible = true
xls.Workbooks.Add
for (i = 0; i < x.length; i++) {
var y = x[i].cells;
for (j = 0; j < y.length; j++) {
xls.cells(i + 1, j + 1).value = y[j].innerText;
}
}
}
</script>


HTML


<input type='button' value='Export To Excel' onclick="exportTable();"/>

Thursday, 11 October 2018

SPQuery: How to filter based on modified date?


<Query>
    <Where>
        <Leq>
            <FieldRef Name="DateColumn" />
            <Value Type="DateTime">
                <Today OffsetDays="-4" /> // Modified in last 4 days
            </Value>
        </Leq> 
    </Where>
</Query> 

Monday, 20 August 2018

How to lock a w2ui grid row and column?



To lock a column:

w2ui['grid'].columns[col_index].editable=false;


To lock a row:

w2ui['grid'].records[row_index].w2ui.editable=false;

-or-

w2ui['grid'].records[w2ui['grid'].get($(this).attr("recid"),true)].w2ui.editable=false;

-or-

records: [
recid: $(this).attr("ows_ID"),
'w2ui':{
       style: {},
       editable:($(this).attr("ows_columnName")=="Some Value")?false:true
      }
]

To lock the full grid:

w2ui.grid.lock('Loading...', true); //second parameter is for the optional spinner


To lock a particular cell:

There is no out-of-the-box method to support this. However, you can target some of the HTML attributes of the cell to achieve this. You will have to look deep into w2ui js files to understand the working of editable cells.

Something like this may work:

$(window).load(function (){
disableCells ();
}

function disableCells()
{
var rowArr=w2ui['grid'].records;

  $(rowArr).each(function() {
        if($(this).attr("Column Name")=="SomeValue")
        {
//column index = 5
//column name = Column5
$("#"+"grid_grid_data_"+w2ui['grid'].get($(this).attr("recid"),true)+"_5").html("<span>"+$(this).attr("Column5")+"<span>");
}
});
}


If windows.load fails to lock the cells then use the following:

$(window).on('load', function () {
w2alert('Welcome message/instruction.').done(function () {
    disableCells();
});
});

Tuesday, 14 August 2018

[Solved] SharePoint designer workflow lookup for number field is returning 0 for the blank fields.


1. One of the ways is to have a workflow variable and assign it to the lookup value. And then comparing it to 0.


2. Other way is to create a calculated text field in the list and use it instead of the number field in the workflow lookup.

Calculated text field =IF([ColumnName]=0,"-",TEXT([ColumnName],0))


=TEXT([Column],<format>) is used to avoid unwanted zeros after the decimal point. Without this, the final value for the calculated text field would look something like 123.000000000

 <format> is a number format in text format. e.g. 0; 0.0; 0.00; etc.

Friday, 10 August 2018

How to get a cell value from w2ui grid?


var changeArr=w2ui['grid'].getChanges();

$(changeArr).each(function() {

 test = $(w2ui['grid'].get(this.recid)).attr("ColumnName");

//OR

test = w2ui['grid'].getCellValue(w2ui['grid'].get($(this).attr("recid"),true), column_index) ;

});


Tuesday, 7 August 2018

How to add total row at the bottom of a w2ui grid?


$('#grid').w2grid({
    name    : 'grid',
    columns: [               
        { field: 'recid', caption: 'ID', size: '50px' },
        { field: 'lname', caption: 'Last Name', size: '30%' },
        { field: 'fname', caption: 'First Name', size: '30%' },
        { field: 'email', caption: 'Email', size: '40%' },
        { field: 'sdate', caption: 'Start Date', size: '120px' },
        { field: 'sdate', caption: 'End Date', size: '120px' }
    ],
    records: [
        { recid: 1, fname: 'John', lname: 'doe', email: 'vitali@gmail.com', sdate: '1/3/2012' },
        { recid: 2, fname: 'Stuart', lname: 'Motzart', email: 'jdoe@gmail.com', sdate: '2/4/2012' },
        { recid: 3, fname: 'Jin', lname: 'Franson', email: 'jdoe@gmail.com', sdate: '4/23/2012' },
        { recid: 4, fname: 'Susan', lname: 'Ottie', email: 'jdoe@gmail.com', sdate: '5/3/2012' },
        { recid: 5, fname: 'Kelly', lname: 'Silver', email: 'jdoe@gmail.com', sdate: '4/3/2012' },
        { recid: 6, fname: 'Francis', lname: 'Gatos', email: 'vitali@gmail.com', sdate: '2/5/2012' }
    ],
    summary: [
        { recid: 10, fname: 'John', lname: 'doe', email: 'vitali@gmail.com', sdate: '1/3/2012' }
    ]
});


Source: http://w2ui.com/web/docs/1.5/w2grid.summary

Monday, 6 August 2018

How to hide search box in w2ui grid?


show: {
            //...
            toolbarSearch: false,
            searchAll: false,
            toolbarInput: false,
            //...
        },

Friday, 3 August 2018

InfoPath: How apply formatting rule of a date field?


Add the 'Date' field to the form, and change the control to 'Text Box'

Thursday, 2 August 2018

How to add custom buttons in w2ui grid?


toolbar: {
        items: [
            { type: 'break' },
            { type: 'button', id: 'mybutton', caption: 'My other button', img: 'w2ui-icon-check' }
        ],
        onClick: function (event) {
            switch (event.target) {
                case 'mybutton':
                    //business logic here
                    break;
            }
    },

How to execute w2ui delete event without warning message?


w2ui.grid.on('delete', function(event) {
    event.force = true;
    //console.log('No confirmation required');
});

OR

onDelete: function (event) {
        event.force = true;
...
}

Wednesday, 1 August 2018

How to add conditional style in w2ui grid to highlight individual cell?


Add following while preparing records array:

    'w2ui':{style: {
      10: ($(this).attr("ows_Column1")=="Approved")?"background-color: green":"red",
      11: ($(this).attr("ows_Column2")=="Approved")?"background-color: yellow":"",
      }}


To highlight specific header:

<style type="text/css">
td[col="6"].w2ui-head,td[col="7"].w2ui-head {
    border:dashed 2px #0099f8 !important;
    font-weight:bold;
}
</style>


Tuesday, 31 July 2018

How to add more than 5 conditions in InfoPath form's rule?


1. Add the first condition.

2. Change the type of condition to 'The expression'.

3. Open a text editor and paste the above expression.

4. Do the same for all the conditions.

5. Formulate the overall conditions by adding and, or between the above conditions.

6. Add the final expressions as a single condition (The expression).


Note: The final expression should be typed in a single line of the text editor.

Wednesday, 2 May 2018

SharePoint: How to use IF condition in InfoPath form formula?


if (BoolCondition) {
   TrueResult
}
else {
   ElseResult
}


becomes

concat(

substring(TrueResult, 1, (BoolCondition) * string-length(TrueResult)),

substring(ElseResult, 1, (not(BoolCondition)) * string-length(ElseResult)))


Source: https://blogs.msdn.microsoft.com/infopath/2006/11/27/conditional-default-values/

Tuesday, 17 April 2018

[Solved] SPServices : GetListItems not returning all items from SharePoint list?


'GetListItems' will return items from default list view only.

To overcome this use the following filters:

var cmlQuery="<Query><Where><Neq><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Neq></Where></Query>";

CAMLQuery: cmlQuery//Include items which are filtered-out in default view
CAMLRowLimit: 0//Override default view row-limit

Friday, 13 April 2018

How to increase the width of a column in SharePoint 2013 list?


Add the following in script editor:

<style type='text/css'>
.ms-vh-div[DisplayName='Column Display Name']
{
  width:400px;
}
</style>

Thursday, 12 April 2018

Friday, 6 April 2018

How to mass check-in SharePoint library files?


Here is a way to check in multiple files at once:

First, if you don't have ownership of the files then go to library settings. Click on 'Manage files with no checked in version'. Select all and take ownership.

If not already available, create a view with filter as following: 'Check Out To' = [Me].

Go to content and structures from site settings. Go to the view you just created. Select all files and check-in using the action tab.

Tuesday, 3 April 2018

SPServices : How to prepare date data for the SharePoint list date field using JavaScript?


var currDate = new Date();

var numDay=currDate.getDate();
var numMonth = currDate.getMonth();
var numYear = currDate.getFullYear();

var tempDate = (++numMonth)+"/"+(numDay)+"/"+numYear ;
var spDate = new Date(tempDate).toISOString();

//e.g. 2019-08-29T18:30:00.000Z


Note: You may have to adjust numDay based on the timezone.

How to fetch the email of the current user using SPServices?



$( document ).ready(function(){

 currUser = $().SPServices.SPGetCurrentUser({

  fieldNames: ["WorkEmail"],

  debug: false

 });

currUserEmail = currUser.split('p|')[1];

})

How to find the day number from today's date in SharePoint designer 2013?




How to split a string in SharePoint 2013 designer workflow to extract a substring?



How to activate SharePoint 2013 workflows on a SharePoint Online site?


Go to site settings > Workflow settings > Workflow Health > Activate

Monday, 2 April 2018

How to update text and tooltip of default save button in w2ui grid?


var btn = w2obj.grid.prototype.buttons;
btn['save'].text = w2utils.lang('New Text');

btn['delete'].text = w2utils.lang('Reject Selected');
btn['delete'].tooltip = null;

Sunday, 1 April 2018

CAML Query : How to put four AND conditions?


<And>
    <Eq>condition</Eq>
    <And>
        <Eq>condition</Eq>
        <And>
            <Eq>condition</Eq>
            <And>
                <Eq>condition</Eq>
                <Eq>condition</Eq>
            </And>
        </And>
    </And>
</And>

Saturday, 31 March 2018

CAML Query : How to query for SharePoint list items with special characters in value?


Use CDATA like below:

var camlQuery="<Query><Where><Eq><FieldRef Name='Column Name'/><Value Type='Text'><![CDATA[" + decodeURI(getParameterByName('queryStringParameter',window.location.href))+ "]]></Value></Eq></Where></Query>";

How to get and update SharePoint list using SPServices and w2ui grid table?

Sample Page (SharePoint Designer):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta name="WebPartPageExpansion" content="full" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Page Title</title>
<script type="text/javascript" src="https://domain.com/sites/siteName/SiteAssets/scripts/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="https://domain.com/sites/siteName/SiteAssets/scripts/jquery.SPServices.min.js"></script>
<script type="text/javascript" src="https://domain.com/sites/siteName/SiteAssets/scripts/w2ui-1.5.rc1.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://domain.com/sites/siteName/SiteAssets/scripts/w2ui-1.5.rc1.min.css" />

<script language="javascript" type="text/javascript">

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}


var cmlQuery="<Query><Where><Eq><FieldRef Name='Column Name'/><Value Type='Text'><![CDATA[" + decodeURI(getParameterByName('queryStringParameter',window.location.href))+ "]]></Value></Eq></Where></Query>";

var listData=[];
var counter=0;

$(document).ready(function() {
  $().SPServices({
    operation: "GetListItems",
    async: false,
    listName: "List Name",
    CAMLViewFields: "<ViewFields Properties='True' />",
    CAMLQuery: cmlQuery,
    CAMLRowLimit: 0,
    completefunc: function (xData, Status) {
      $(xData.responseXML).SPFilterNode("z:row").each(function() {
      listData.push({recid: $(this).attr("ows_ID"),Boolean: ($(this).attr("ows_Check_x0020_Box")=="1"),Resource: $(this).attr("ows_Enterprise_x0020_ID").split('#')[1]});
      });
    }
  });
});

function UpdateItem(_id,_boolean)
{
$().SPServices({
operation: "UpdateListItems",
    listName: "List Name",
    ID: _id,
    valuepairs: [["Check_x0020_Box", _boolean]],
    completefunc: function (xData, Status) {
        //alert(Status);
    }
});
}

$(function () {
    $('#grid').w2grid({
        name: 'grid',
        show: {
            toolbar: true,
            footer: true,
            toolbarSave: true
        },
        columns: [             
//            { field: 'recid', caption: 'ID', size: '50px', sortable: true, resizable: true,show:false },
            { field: 'Boolean', caption: 'Boolean', size: '60px', sortable: true, resizable: true, style: 'text-align: center',
                editable: { type: 'checkbox', style: 'text-align: center' }
            },
            { field: 'Resource', caption: 'Resource', size: '120px', sortable: true, resizable: true}
        ],
     
        onSave: function (event) {
        var changeArr=w2ui['grid'].getChanges();
        $(changeArr).each(function() {
        UpdateItem($(this).attr("recid"),$(this).attr("Boolean"));
        });
            w2alert('Saved!');
         
        },

   
        records:listData
    }); 
 
    if(w2ui['grid'].records.length==0)
    {
    $("#grid").hide();
    w2alert('No pending items. Thanks!');
}

});



</script>

</head>

<body>
<div id="grid" style="width: 100%; height: 400px;"></div>
</body>


</html>

Friday, 30 March 2018

How to add cell borders in SharePoint list view?


Add following in a script editor:


<style>
    /* Table Rows*/
    /* Set background for every row */
    .ms-listviewtable > tbody > tr {
        background: white;
    }

    /* Set border for every row */
    .ms-listviewtable > tbody > tr td{
        border-bottom: 1px solid #AFAFAF !important;
        border-left: 1px solid #AFAFAF !important;
        border-right: 1px solid #AFAFAF !important;
    }

    /* Set background for every alternating row */
    .ms-listviewtable > tbody > tr.ms-alternating {
        background: #E2E3E5;
    }

    /* Header Row */
 
    .ms-listviewtable tr.ms-viewheadertr {
        background: transparent;
    }

    /* Modify background color */
    tr.ms-viewheadertr > th.ms-vh-icon, /* Input box and attachment icon */
    tr.ms-viewheadertr > th.ms-vh, /* Text */
    tr.ms-viewheadertr > th.ms-vh2,
    tr.ms-viewheadertr > th /* Text */ {
        background: #e2e3e5;
    }

    /* Modify background color on hover */
    tr.ms-viewheadertr > th.ms-vh:hover,
    tr.ms-viewheadertr > th.ms-vh2:hover,
    tr.ms-viewheadertr > th  {
        background-color: #e2e3e5;
        border-color: #e2e3e5;
    }

    /* Modify font color */
    .ms-viewheadertr a,
    .ms-viewheadertr div {
        color: black;
        font-weight: bold;
    }

    /* Modify font color on hover */
    .ms-viewheadertr a:hover,
    .ms-viewheadertr div:hover {
        color: black;
        font-weight: bold;
    }
    tr.ms-viewheadertr > th.ms-vh-icon:last-child {
        display:none;
    }

</style>

[Solved] w2ui table rows not displaying data.


Try using jQuery 2.2.4 or below.

w2ui is not compatible with the higher versions of jQuery.

Tuesday, 27 March 2018

SharePoint : How to make a drop down read-only in an InfoPath form?


Add a rule on the drop down of  type 'Formatting'.

Add some condition which would be always true.

e.g. 'Expression' = true()

Choose to disable the control

Monday, 26 March 2018

How to export SharePoint survey into an Excel file with date fields?


Go to the survey actions and click on Export to spreadsheet.



If you want to include any of the missing fields then open the 'Overview' list view of the survey in SharePoint designer. Add the missing fields like below in the advanced mode.

    <ViewFields>
<FieldRef Name="Created"/>
<FieldRef Name="Author"/>
<FieldRef Name="Sample_x0020_Text"/>
</ViewFields>

Monday, 19 March 2018

How to get item id using GUID in SharePoint 2013 designer workflow?


'Create item in' action in SharePoint 2013 designer workflow returns GUID instead of item ID.

Use the lookup like below to fetch the ID of the newly created item.


Thursday, 22 February 2018

SharePoint : How to make a field mandatory based on another field, in a datasheet list view?


You can use List Settings -> Validation Settings for this.

e.g. =IF([Replacement Available]="Yes",IF([Replacement]="",FALSE,TRUE,TRUE)

This formula would affect the default 'new item' form as well.

Wednesday, 21 February 2018

[Solved] SharePoint : The selected user(s) may not be valid on the site this workflow is published on.


Sending emails to external users:

If an email address is skipped by the SharePoint 2013 workflow then, instead of adding the email address directly into the TO/CC list add it using a workflow variable.

Create a workflow variable of type string. Assign the email address as value to this variable. And use this variable in the workflow Email.

Make this variable to return Login Name instead of string.




Also, to send emails to external users use the 2010 template of workflow instead of the 2013.

2013 workflows skips the external users while sending mailers.

Tuesday, 20 February 2018

SharePoint : How to use [Today] in a calculated field?


Option 1: Create a field named 'Today'. Use it in the formula. Now, delete the 'Today' field.

Option 2 (recommended): If possible, use list views instead. You can use [Today] under filter options.

Here you can compare a date field with [Today]+/-SomeNumber.

Example: Date Field1 < [Today]+100

[Solved] SharePoint : No item exist at URL. It may have been deleted or renamed by another user.


Check whether the user has required permission on the list/item or not?

Thursday, 15 February 2018

SharePoint List View: How to restrict access to a list view?


1. Edit the page.
2. Edit list view web-part.
3. Advanced > Target Audiences - Specify the SharePoint group here.

Done!

Monday, 12 February 2018

How to trigger SharePoint workflow mailers only on weekdays?


Add a delay before triggering mailer like below:



InfoPath Form: How to fetch current user email?


Current Logged in User

SharePoint On-premise: substring-after(userName(), "\")

SharePoint Online: substring-after(substring-after(userName(), "|"), "|")


From People Picker Field

SharePoint On-premise: concat(substring-after(AccountId, "\"), "@company.com")

SharePoint Online: substring-after(substring-after(AccountId, "|"), "|")