Quantcast
Channel: SharePoint JavaScripts
Viewing all 391 articles
Browse latest View live

AD-Group in SP-Group: Workaround for verifying membership

$
0
0
Change log
January 12, 2016
Fixed a bug with using “getByTitle” and not the correct “getByName” in the SP 2010 code example.

This is a workaround for verifying membership in a SharePoint group when the user is added to the group as a member in an AD-group, and not as an individual user.

You find two code examples below. The first one will work in SP 2013 only, but the last will work in both SP 2010 and SP 2013 (not SP 2007).

Disclaimer: I have NOT been able to test this as I don’t have any AD groups to add in my SP 2013 Office 365 test site.

Based on this post by Eric Alexander

How to set up a trigger in DFFS

In DFFS backend – add this code to the Custom JS:

SharePoint 2013:

function spjs_isCurrentUserInGroup(groupIdOrName){
 var endpoint;
 if(typeof groupIdOrName === "string"){
 endpoint = _spPageContextInfo.webAbsoluteUrl+"/_api/web/sitegroups/getbyname('"+groupIdOrName+"')/CanCurrentUserViewMembership" 
 }else{
 endpoint = _spPageContextInfo.webAbsoluteUrl+"/_api/web/sitegroups("+groupIdOrName+")/CanCurrentUserViewMembership" 
 }
 return jQuery.ajax({ 
 "url":endpoint,
 "type":"GET", 
 "contentType":"application/json;odata=verbose",
 "headers":{ 
 "Accept": "application/json;odata=verbose"
 }
 });
}

function checkADGroupMembership(){
 spjs_isCurrentUserInGroup(18).success(
 function(data){
 if(data.d.CanCurrentUserViewMembership){
 setTimeout(function(){
 spjs.dffs.triggerRule(["isInADGroup"]);
 },10);
 }
 }
 );
}

SharePoint 2010:

function spjs_isCurrentUserInGroup(groupIdOrName){
 var cc, gc, g, u;
 cc = new SP.ClientContext.get_current();
 gc = cc.get_web().get_siteGroups();
 if(typeof groupIdOrName === "string"){
 g = gc.getByName(groupIdOrName);
 }else{
 g = gc.getById(groupIdOrName);
 } 
 u = g.get_users();
 cc.load(u);
 cc.executeQueryAsync(
 function(sender, args){
 setTimeout(function(){
 spjs.dffs.triggerRule(["isInADGroup"]);
 },10);
 },
 function(sender, args){
 // No access
 }
 );
}

function checkADGroupMembership(){
 // 18 is the ID of the group
 spjs_isCurrentUserInGroup(18);
}

The number 18 in the function “checkADGroupMembership” is the group id, but you can also use the display name of the group – change it to match your group.

Add a rule to DFFS with the “Rule friendly name”:

isInADGroup

This rule is set up with the trigger “No trigger (must be triggered manually), and with all the actions you want to apply if the rule is triggered.

As this is a “manual trigger rule”,  you must add another rule to trigger this one when the form has loaded. This is necessary because the REST call cannot be used with the trigger “Custom JavaScript functions” directly.

To trigger the REST call / JSOM query, and the following trigger of the DFFS rule if the user is member of the group is done by another DFFS rule triggering on “The form is ready”.

Set this one up with the function name “checkADGroupMembership” in the “Run these functions / trigger these rules” field.

If the logged in user is member of the SharePoint group as a member in an AD-group, the rule “isInADGroup” will be triggered.

I hope this makes sense, and if not – post a comment below or in the forum.

Alexander


New BETA of DFFS v4.365

New version of CommentBox for SharePoint

$
0
0

I have updated CommentBox for SharePoint with the following changes:

  • Tidied up the code and added support for adding attachments to comments. You can add as many attachments as you like, and they will be listed below the comment.
  • You can also upload imaged directly from the “insert” menu to have them appear inline in the comment.
  • With some restrictions (browser related) you can also paste images from the clipboard directly in the comment textarea.
  • These images are stored as a base64 encoded string inline in the comment, so don’t add very large images this way.
  • Hover over image attachments to show a preview, click, to open in a dialog.

If you have an existing license code, you can request an updated code for this version at no extra cost.

Use the forum for comments and questions

Alexander

Time tracker in a DFFS enabled list

$
0
0

Here is an example of a simple time tracker in a DFFS enabled list.

Before you start you must set up DFFS. You find more info here.

Create the list

Create a custom list, and add these fields. Ensure you use the exact same FieldInternalName as described here. When the field has been created, you can change the name to whatever you like.

  • Title (Default field already present in the list)
  • Description (Multiple lines of text ) – This field is optional, and not required in the solution.
  • StartTimeString (Single line of text
  • TotalTimeString (Single line of text)
  • Activity (Multiple lines of text – plain text)
  • Log (Multiple lines of text – plain text)
  • TotalTime (Calculated) – with this formula – output as “Single line of text”:
    =TEXT(INT(TotalTimeString/1000)/86400,"hh:mm:ss")
  • Ticking (Calculated) – with this formula – output as “Yes/No”:
    =StartTimeString<>""

Configure DFFS

Enter DFFS backend in NewForm and EditForm, and set up DFFS like this (you can create NewForm first, and then clone it to EditForm):

TimeTrackerInDFFS_1

TimeTrackerInDFFS_2

TimeTrackerInDFFS_3

TimeTrackerInDFFS_4

Then add this code to the Custom JS textarea:

(function(){
 var a = [], b = [], tt;
 a.push("<tr style='font-size:18px;color:green;'>");
 a.push("<td colspan='2' style='padding:2px;'>");
 a.push("<span id='elapsedTime'></span><span id='totalTime'></span>"); 
 a.push("</td>");
 a.push("</tr>");
 $("table.ms-formtable").prepend(a.join(""));
 b.push("<span title='You can save and close the list item while the timer is running. It will keep tracking time until you edit the item and click \"Stop the timer\".'>");
 b.push("<input style='background-color:#C2CF8A;color:#444;' type='button' id='dffsTimeTrackerStartBtn' value='Start the timer' onclick='startTicker()'>");
 b.push("<input style='background-color:#D57C7C;color:#ffffff;display:none;' type='button' id='dffsTimeTrackerStopBtn' value='Stop the timer' onclick='stopTicker()'>");
 b.push("<span>&nbsp;</span>");
 b.push("</span>");
 $("input[id$='_diidIOSaveItem']:last").before(b.join(""));
 tt = getFieldValue("TotalTimeString");
 if(tt !== ""){
 $("#elapsedTime").html("Total time: "+getFriendlyTime(Number(tt)));
 }
})();

function startTicker(){
 var a= getFieldValue("StartTimeString");
 if(a === ""){
 setFieldValue("StartTimeString",new Date().valueOf());
 $("#dffsTimeTrackerStartBtn").hide();
 $("#dffsTimeTrackerStopBtn").show();
 $("#totalTime").html("");
 }
}

function stopTicker(){
 var a = getFieldValue("StartTimeString")
 , b = new Date().valueOf()
 , u = spjs.utility.userInfo(_spPageContextInfo.userId)
 , et = b-Number(a)
 , tt = Number(getFieldValue("TotalTimeString")) + et
 , log = getFieldValue("Log")
 , al = getFieldValue("Activity");
 setFieldValue("TotalTimeString",Number(tt));
 // Reset start time and log
 setFieldValue("StartTimeString","");
 setFieldValue("Activity","");
 if(a !== ""){
 if(log !== ""){
 log += "\n*******************\n";
 }
 if(al !== ""){
 al = "\n\nActivity log:\n"+al;
 }
 setFieldValue("Log",log+u.Title+"\nStart: "+new Date(Number(a)).toLocaleString(_spPageContextInfo.currentUICultureName)+"\nEnd: "+new Date().toLocaleString(_spPageContextInfo.currentUICultureName)+"\nElapsed time="+getFriendlyTime(et)+al);
 }
 $("#elapsedTime").html("");
 $("#totalTime").html("Total time: "+getFriendlyTime(tt));
 $("#dffsTimeTrackerStartBtn").show();
 $("#dffsTimeTrackerStopBtn").hide();
}

function getFriendlyTime(ms){
 var h, m, s;
 h = Math.floor(ms / 3600000);
 m = Math.floor((ms % 3600000) / 60000);
 s = Math.floor((ms % 60000) / 1000);
 return (h<10?"0"+h:h)+":"+(m<10?"0"+m:m)+":"+(s<10?"0"+s:s);
}

if(getFieldValue("StartTimeString") !== ""){
 $("#dffsTimeTrackerStartBtn").hide();
 $("#dffsTimeTrackerStopBtn").show();
}

setInterval(function(){
 var a = getFieldValue("StartTimeString"), b = new Date().valueOf(), tt = Number(getFieldValue("TotalTimeString"));
 if(a !== ""){
 $("#elapsedTime").html("Elapsed time: "+getFriendlyTime(b - Number(a))); 
 if(tt !== ""){
 $("#elapsedTime").append(" / Total time: "+getFriendlyTime(tt + (b - Number(a))));
 }
 } 
},1000);

Final result

When you press “Start the timer”, this is how it looks in the form:

TimeTrackerInDFFS_5

When you stop the timer, the total time is displayed like this:

TimeTrackerInDFFS_6

If you restart the timer again, it will count the current elapsed time, and the total time like this:

TimeTrackerInDFFS_7

You can save the list item with the timer running. When you  edit it again afterwards, press “Stop the timer” and save the item.

This is how it looks in the list view:

TimeTrackerInDFFS_8

Please note that the “TotalTime” field will only show the time after the timer has been stopped, and will not show the “live ticker”.

Post any questions in the forum for DFFS here

Alexander

 

DFFS v4.365 released

$
0
0

Finally, after a long BETA period, latest version of Dynamic forms for SharePoint is released.

DFFS v4.365 – February 29, 2016

  • Added support for using DFFS with DocumentSets.
  • Added new trigger “Workflow status” that lets you check the status on a workflow in the current item.
  • Added option to share the Field CSS configuration between different forms in the same list.
  • Added new option to preserve the selected tab when navigating from DispForm to EditForm in a list item. You find this setting in the Misc tab.
  • Split the “showTooltip” out in a separate function to let advanced users override it.
  • Added new functionality to show a list of empty required fields above the form when the save is halted. The list is clickable and will take you to the correct tab / accordion and highlight the field. You can turn this feature on in the Misc tab. Please note that you must update the CSS files also.
  • Added option to set the default “To” and “Cc” in the “E-Mail active tab” feature to a people picker in the current form, or to a fixed email address.
  • Added option to send E-Mails from DFFS rules. You can configure the E-Mail-templates in the new “E-Mail and Print” tab in DFFS backend. Added support for delaying an email until a set “Send date” has been reached. Please note that this is only possible if you use the “Use custom list with workflow to send E-Mails”, and is not when using the built in functionality for sending E-Mails in SP 2013 (REST). You find more information on the help icon in the “E-Mail and Print” functionality in DFFS backend, and in the user manual. You find a video describing the workflow setup in the user manual.
  • Changed the “target” on the link to a document of type “pdf” or “txt” in a DFFS dialog so it will open in a new window.
  • For SP2007: Made the “Return to DispForm when editing an item and NOT opening the form in a dialog” checkbox visible in the Misc tab.
  • Fixed a possible backwards compatibility issue when using the latest version of DFFS with a configuration saved with an older version.
  • Fixed some issues with using “content type” as trigger in a DFFS form.
  • In triggers on date and time columns: added support for comparing with today like this:
    [today]+14 or [today]-5

    The number is the number of days you want to offset the value with. This same functionality can be used when comparing with a value pulled from another date and time column in the form – like this:

     {NameOfField}+14 or {NameOfField}-5
  • Changed the “debug output” to make it easier to read by collapsing some sections initially.
  • Fixed a bug with hiding a field by a rule while using the accordion functionality.
  • Fixed the “change trigger” on date columns so it will trigger the change event on invalid dates.
  • Changed the backend code for detecting the change of a PeoplePicker field.
  • Added support for using People pickers as trigger in SP 2007 and 2010. This requires that you update SPJS-Utility.js. This may not work 100% in all cases – post any findings in the forum.

You find the full change log here: http://spjsblog.com/dffs/dffs-change-log/

User manual

The user manual has been updated with the latest changes: http://spjsblog.com/dffs/dffs-user-manual/

Post any question in the forum

http://spjsblog.com/forums/forum/dynamic-forms-for-sharepoint/

Alexander

DFFS: Start SP2013 workflow from a button in a list item

$
0
0

The approach described below requires Dynamic forms for SharePoint to be set up in the form. You find DFFS here.

For this to work, your workflow must be set up to start manually, then you must go to the page where you can start the workflow and look at the button / link to get the “subscriptionId”. To do this, you can right click the button and select “inspect”. This opens the developer console and you can see the link like this:

<a href="javascript:StartWorkflow4('ab064e56-926c-477b-910e-0d3759f5b956', '12', '{18C41B2A-4C33-482F-BFC5-C06B92072B10}')" id="UI_Auto_ab064e56-926c-477b-910e-0d3759f5b956">ExampleWF</a>

The “subscriptionId” is the first parameter in the StartWorkflow4 function.

When you have the “subscriptionId”, add this to the custom js textarea in the DFFS:

spjs.workflow = {
	"text":{
		"successMessage":"The workflow was started",
		"errorMessage":"Something went wrong. To try again, reload the page and then start the workflow."
	},
	"data":{
		"dlg":null
	},
	"initListItemWF":function(subscriptionId){
		if(typeof SP.WorkflowServices === "undefined"){
			jQuery.getScript(_spPageContextInfo.webServerRelativeUrl+"/_layouts/15/sp.workflowservices.js",function(){
				spjs.workflow.start(subscriptionId);
			});
		}else{
			spjs.workflow.start(subscriptionId);
		}
	},
	"start":function(subscriptionId){
		var itemId = GetUrlKeyValue("ID");
		spjs.workflow.showProgress();
		var ctx = SP.ClientContext.get_current();
		var wfManager = SP.WorkflowServices.WorkflowServicesManager.newObject(ctx, ctx.get_web());
		var subscription = wfManager.getWorkflowSubscriptionService().getSubscription(subscriptionId);
		ctx.load(subscription, 'PropertyDefinitions');
		ctx.executeQueryAsync(
			function(sender, args){
				var params = new Object();
				var formData = subscription.get_propertyDefinitions()["FormData"];
				if(formData != null && formData != 'undefined' && formData != "")
				{
					var assocParams = formData.split(";#");
					for(var i = 0; i < assocParams.length; i++)
					{
						params[assocParams[i]] = subscription.get_propertyDefinitions()[assocParams[i]];
					}
				}
				wfManager.getWorkflowInstanceService().startWorkflowOnListItem(subscription, itemId, params);
				ctx.executeQueryAsync(
					function(sender, args)
					{
						spjs.workflow.closeDlg();
						SP.UI.Notify.addNotification(spjs.workflow.text.successMessage,false);
					},
					function (sender, args)
					{
						spjs.workflow.closeDlg();
						alert(spjs.workflow.text.errorMessage);
					}
				);
			},
			function(sender, args)
			{
				spjs.workflow.closeDlg();
				alert(errorMessage);
			}
		);
	},
	"closeDlg":function(){
		if(spjs.workflow.data.dlg != null){
			spjs.workflow.data.dlg.close();
		}
	},
	"showProgress":function(){
		if(spjs.workflow.data.dlg == null){
			spjs.workflow.data.dlg = SP.UI.ModalDialog.showWaitScreenWithNoClose("Please wait...", "Waiting for workflow...", null, null);
		}
	}
};

Then you can insert a HTML Section to one of your DFFS tabs with this code:

<input type="button" onclick="spjs.workflow.initListItemWF('ab064e56-926c-477b-910e-0d3759f5b956')" value="Start WF">

Post any questions in the forum.

Alexander

Upcoming changes in license types and price for DFFS

$
0
0

The following changes to the Dynamic forms for SharePoint license types (and prices) will take effect on April 1, 2016.

New SITE license

The entry level license for DFFS will be scoped to a single SITE. This new license will be priced at $50.

You can buy as many as these as you like, but if you need more than 5 within the same site collection, you should go for a SITE COLLECTION license.

Changed price on the SITE COLLECTION license

The new price on the SITE COLLECTION license will be $250.

The reason for this relatively large increase in price on the SITE COLLECTION license is basically that I have priced this to low from the very beginning.

The current price simply doesn’t cover the time I spend supporting and developing the solution.

This change will NOT be applied retroactively, and will therefore not affect SITE COLLECTION licenses purchased prior to this date.

Partner program

From the same date these changes take effect, I’ll update the “reward program / partner program” to let individual consultants or other companies register as partners.

More information about the “application” for partners will be published soon.

The “Consultant license” will no longer be in use after this change takes effect.

Payback

Partner that conveys the sale of a SITE COLLECTION (or better) license will be eligible to receive a 10% payback. This payback requires the partner to be registered prior to the purchase, and requires a PayPal account (to receive the payback).

CommentBox for SharePoint – now with e-mail alerts on SharePoint 2013

$
0
0

By request I have updated CommentBox for SharePoint with an option to subscribe to comments.

Please note that this is a BETA version, and I will need some feedback on this new feature.

You can turn on two levels of subscription. One is a subscription to all new comments:cbox_subscribe_1

And one to subscribe to all replies to a root comment:

cbox_subscribe_2

The email will look something like this, but you can customize it in the “argument object”:

cbox_subscribe_3

This new feature is ONLY available in SharePoint 2013 – it is not visible in SP 2010 and because it uses the SP 2013 exclusive REST-Email feature, it WILL NOT work in SP 2010.

Please note that you must update the ” argument object” in your CEWP / setup with a few new variables – all are marked with “New in v2.6” and can be found in the file “spjs-cBox_CEWP.js.txt” in  the download package.

You must update all the files from the download package. See this page to get the files and for setup instructions (not updated with all features from this BETA – look at the file “spjs-cBox_CEWP.js.txt” in the download package for all new variables).

Remember this is a BETA version, and post any comments in the forum.

Alexander


New version of DFFS – only bugfixes

$
0
0

I have published an updated version of the DFFS package. This one has only bugfixes, and no new features. You find the change log here: http://spjsblog.com/dffs/dffs-change-log/

Post any comments in the forum.

Alexander

Extension to the hit-counter for logging hits to files linked in the quick-start

$
0
0

This is an extension to this solution: http://spjsblog.com/2011/05/28/hit-counter-and-star-rating-for-sharepoint/

I got a request for a solution to add hit counter functionality to a set of custom HTML pages in a document library. While you can add the hit counter code to the page, it will be a bit cumbersome if you have pages not inheriting from the master page.

I will here describe a possible solution to the problem, but this requires you to access these files from a link in for example the quick launch. It will not work if you go to the document library directly and open the file.

The code

Add a web part page to a document library in your site. Add a HTML form web part, or a SCRIPT editor web part to the page, and add this code:

<div style="font-size:25px;color:green;">Please wait while we open the requested page...</div>
<script type="text/javascript" src="/SPJS/DFFS/plugins/jquery.js"></script>
<script type="text/javascript" src="/SPJS/DFFS/plugins/SPJS-utility.js"></script>
<script type="text/javascript">

var hitCounterListName = "HitCounter";
var hitCounterListBaseUrl = "";

function spjs_logHitAndRedirect(){
	var redirTo = GetUrlKeyValue("goto"), res, data = {};	
	if(redirTo !== ""){
		data.Title = "Hit";
		data.URL = unescape(redirTo);
		data.User = (typeof _spUserId !== "undefined" ? _spUserId : _spPageContextInfo.userId);
		data.ReferringURL = document.referrer;
		res = spjs_addItem({
			"listName":hitCounterListName,
			"listBaseUrl":hitCounterListBaseUrl,
			"data":data
		});
		if(!res.success){
			alert(res.errorText);
		}else{
			location.href = redirTo;
		}
	}else{
		alert("Append \"?goto=[url to page] to the URL to log a hit, and redirect to the page.");
	}
}

_spBodyOnLoadFunctions.push(spjs_logHitAndRedirect);
</script>

You must edit the code and add the correct link to jQuery and spjs-utility.js. You must also provide the correct name and path to the HitCounter list in the variables “hitCounterListName” and “hitCounterListBaseUrl”. This should be the same as you use in the “argObj” in the hit counter setup.

How to use

The link to the HTML page you add to the quick start must be on this format:

https://contoso.sharepoint.com/SitePages/ThePageWhereYouPutTheCode.aspx?goto=https://contoso.sharepoint.com/DocumetLibrary/YourFile.html

The above will log a hit on “https://contoso.sharepoint.com/DocumetLibrary/YourFile.html” and redirect you to this file.

Alexander

DFFS now with built in check-out for list-items

$
0
0

I have previously show how you can use DFFS rules to require check out of list items before editing.

This worked reasonably well in most cases, but if you had a large form with lots of rules, the loading would take twice the time because all the DFFS rules would have to run before the check-out action could take place – and then the form was reloaded.

To overcome this, and also make the setup easier, I have now built support for requiring check-out of list items into DFFS. You find the settings in the Misc tab when editing the EditForm of a list item.

Please note that this is in BETA (v4.3.68), and I need your feedback to ensure it works as expected before releasing it in the production version.

You find the DFFS package in the DFFS_BETA folder in the download section.

Please post any findings in the forum

Alexander

Charts for SharePoint v5 is finally here

$
0
0

I published the first version of the SPJS Charts for SharePoint back in 2010, and released the current v4 version well over 2 years ago.

After being neglected for far to long, I’m happy to finally release v5 of SPJS Charts for SharePoint in a BETA version.

Charts_v5_config

This version has been brushed up quite a lot, and supports most of the chart types available in the Google chart solution.

I have also added support for basic drill-down, transpose and a few other new features. It still supports all SharePoint versions, but I have not been able to test it in SP 2007 – feedback is appreciated.

This new version will not interfere with v4 of SPJS Charts for SharePoint (uses a separate configuration list), but you cannot use v4 and v5 in the same page. You cannot currently import existing charts from v4, but this might be added as an option if there is demand for it.

There is no trial period built in, but you can request a 1-3 month trial by following the link in the banner below the chart.

Follow these simple steps to install

  1. Download the files form here
  2. Unzip, and upload to a document library named “SPJS”. The folder structure should be “/SPJS/Charts/”.
  3. Edit the file “SPJSChartsMaster_CEWP.html” to correct all the links to the various scripts.
  4. Copy the path to the file “SPJSChartsMaster_CEWP.html” and insert the link in the Content link field in a Content Editor Web Part (CEWP) in a page in your site.

Localize the frontend UI

You can edit the file “/SPJS/Charts/js/spjs-charts-i18n.js” to add your own translation for the labels and messages in the frontend UI.

User manual

The user manual is not ready – I’ll update it soon.

Feedback and comments

Please post any feedback in the forum

Charts for SharePoint v5 BETA 3

Charts for SharePoint v5 BETA 4

Charts for SharePoint v5 is ready


DFFS and new form layout in SharePoint

$
0
0

This is a little status update on the new layout in document libraries that are starting to roll out in SharePoint online.

DFFS will currently not work with this new layout. I’m working on a new version that will support it, but until this is ready you must change a setting to keep the classic view.

Read this article that describes how to keep the classic view: https://support.office.com/en-us/article/Switch-the-default-for-document-libraries-from-new-or-classic-66dac24b-4177-4775-bf50-3d267318caa9?ui=en-US&rs=en-US&ad=US

I’ll post updates as soon as I have a BETA ready, but it will most likely be a few months. In any case, it will be ready well before the classic view option is deprecated.

Please post any questions in the forum.

Best regards,
Alexander

Partner registration is finally open

DFFS package has been updated

SPJSFiles (where all the solution files are located) is unavailable

$
0
0

My hosting provider had a sever crash and must rebuild from a backup. This is estimated to take until tomorrow (August 3, 2016).

[The site is up again]

Sorry for the inconvenience,
Alexander

DFFS Installer is now released

$
0
0

I have created a new installer / loader For SP 2010 and 2013. This will ease the setup on SP 2010, and will replace the JSLink installer on SP 2013.

dffs_installer_local

This new installer is part of the effort to support the new design rolling out in SharePoint online.

I will soon publish the Office 365 version of the installer to the Office Store. This will integrate in the ribbon in lists and libraries, but currently only the local version is available. The installation process is described in the user manual.

Please note that the default location for the “SPJS” document library with the DFFS files is in the SITE you use DFFS in.

You can optionally place the “SPJS” document library in the root of the SITE COLLECTION. This is described in the user manual.

This release of DFFS and plugins also features some small new features, and a few bugfixes. You find the complete change log here: http://spjsblog.com/dffs/dffs-change-log/

Please post any questions in the forum

Alexander

 

Viewing all 391 articles
Browse latest View live