Category Archives: Utilities

Inline editing for SharePoint 2007

25.08.2012 v3.0 Fixed a bug where you could not have multiple views of the same list in a page. This update lets you have multiple lists / views of the same list in a page, and have the inline editing feature activated on all of them. The argObj property “myListGuid” is now obsolete. You must use jQuery v1.6 or above. Please note that there are an issue with the frozen header in IE when using jQuery 1.8.


31.05.2012 v2.8 BETA: Added support for single and multi lookup columns.


25.05.2012 v2.7: Added support for frozen list view header in Chrome and Firefox in addition to the existing IE support.


17.05.2012 v2.6.3: Fixing positioning error in IE when scrolling and added a method of clearing a datepicker value by hitting the Delete key when the datepicker is active.


19.02.2012 v2.6 fixed a bug when trying to save “<“, “>” or “&” in a text field. Changed the script to use spjs-utility.js. Note that this version requires jQuery v1.6.4 or newer.


19.02.2012 v2.5 fixes bugs with “pinTableHeader” and grouped views.


28.09.2011 v2.4 fixes a bug preventing this to work with folders.


11.08.2011 v2.3 fixed a bug (from v2.2) that made it impossible to use the solution in document libraries. I have also changed the variables passed to the function “initCustomEditFunction” to an object literal. See updated CEWP below.


08.05.2011 v2.2 makes it possible to use this solution in a web part page alongside other list view web parts.

NOTE:
You can have only one list view web part with this feature activated in one web part page.

Both the CEWP code and the file “inlineEditingForSP2007.js” has changed.


09.02.2011 v2.1 released with this modifications:
Modified the “hover” CSS to highlight the editable TD’s only, and to show a small downarrow in the bottom right corner of the TD.


I have previously created a solution for editing items inline in a list view. You find it here This solution did not support choice fields or multi line text fields.

I stated a long time ago that i would update the solution to support choice fields, but never had the time to implement it. This added feature was requested a few weeks ago, and i had to deliver…

I will put this in a new post as it is completely rewritten.


This solution features inline editing of the following field types in plain list views and in grouped views:

  • Date and Time
  • Single line of text
  • Number
  • Currency
  • Yes/No
  • Person or Group (Single choice)
  • Dropdown choice
  • Radio buttons
  • Checkboxes
  • Multiple lines of text (Plain text)

Hover:
IMG
Edit:
IMG
In Internet Explorer the list view heading row will scroll with the page. This feature is supported in IE only as you cannot have a <tr> with css position:relative in any other browser, and i haven’t had the time to find a workaround.

The code is tested in IE8, Firefox 3.6.13, Chrome 9.0.597.84 and in Safari 5.0.2

It runs much faster than the previous solution – even in large list views. This is due to the method it is created – addressing the <tr> and not each <td> in the first pass. The <td>’s are processed on hover over the <tr>.

You must have the ID column in the view for this solution to work. If you use the option to hide the ID column, it has to be positioned to the far right in th view.

The fields are edited “one at the time” and you must save changes for each individual field.

This solution relies upon “Google Libraries API” to host the jQuery and the jQueryUI. If you prefer local copies, edit the script src in the CEWP code.

Download the code

Get the latest version of the file “InlineEditingForSP2007.js” from here

Put this in a document library or a folder made in SharePoint Designer. Make sure all users have read access to the location. When inserting the CEWP code below, make sure to update the src to reflect your locale copy of the file “InlineEditingForSP2007.js”.

Add this code to a CEWP below the list view

For v2.0-2.2

&lt;link type=&quot;text/css&quot; href=&quot;http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css&quot; rel=&quot;stylesheet&quot; /&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/EditInListView/inlineEditingForSP2007.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
// Set variables
	var dateFormat = 'm/d/yy';
	var boolYesNoText = 'Yes|No';
	var arrToEdit = [];

// If there are only one list view web part in the page, we can rely upon SharePoint to provide the list GUID:
	myListGuid = ctx.listName;

// To use the solution in a web part page with more than one list view web part you must provide the list GUID manually:
	//var myListGuid = &quot;{B9F1D8CF-83DB-4E1A-BF61-752BCB40B2CF}&quot;; // Change this GUID to match your's

// This parameter specifies whether to pin the table header to the top of the screen when scrolling (IE only)
	var pinTableHeader = true;

// The symbol used to mark the boundary between the integral and the fractional parts of a decimal number
	var decimalSeparator = '.'; 

// Hide the ID column
	var hideIdColumn = true;	
// Call function
	initCustomEditFunction(hideIdColumn);
&lt;/script&gt;

For v2.3+

&lt;link type=&quot;text/css&quot; href=&quot;http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css&quot; rel=&quot;stylesheet&quot; /&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/EditInListView/inlineEditingForSP2007.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/spjs-utility.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;

var argObj = {dateFormat:'m/d/yy',
			  decimalSeparator:'.',
			  boolYesNoText:'Yes|No',
			  labelArr:['Save','Cancel','Clear'],
			  arrToEdit:[],
			  myListGuid:'B9F1D8CF-83DB-4E1A-BF61-752BCB40B2CF',
			  pinTableHeader:true,
			  hideIdColumn:true};
	initCustomEditFunction(argObj);	
&lt;/script&gt;

For v3.0+

&lt;link type=&quot;text/css&quot; href=&quot;http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/themes/redmond/jquery-ui.css&quot; rel=&quot;stylesheet&quot; /&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/EditInListView/inlineEditingForSP2007.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/spjs-utility.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;

var argObj = {dateFormat:'m/d/yy',
			  decimalSeparator:'.',
			  boolYesNoText:'Yes|No',
			  labelArr:['Save','Cancel','Clear'],
			  arrToEdit:[],
			  pinTableHeader:true,
			  hideIdColumn:true};
	initCustomEditFunction(argObj);	
&lt;/script&gt;

New in v2.6
I have removed some functions from the file “inlineEditingForSP2007.js” and you must refer spjs-utility.js in the CEWP

New in v3.0
The argObj property “myListGuid” is now obsolete.

Parameters explained:

  • dateFormat: This must reflect the current regional settings for the picker to “pick up” the date in the field and display it correctly in the datepicker.
  • boolYesNoText: Used to display Yes or No in the field when it is changed. Only cosmetics as the “real” value is 0 or 1.
  • labelArr: The text on the links when in edit mode on a field. New in v2.3
  • arrToEdit: Optional. To restrict edit to a selection of fields, enter them here by FieldInternalName in an array format. Defaults to All editable fields in the current view.
  • myListGuid Obsolete in v3.0: If there are only one list view web part in the page, we can rely upon SharePoint to provide the list GUID using
    myListGuid = ctx.listName
  • myListGuid Obsolete in v3.0: To use the solution in a web part page with more than one list view web part you must provide the list GUID manually
    myListGuid = PutTheListGuidHere
  • pinTableHeader: This parameter specifies whether to pin the table header to the top of the screen when scrolling (IE only)
  • decimalSeparator: The symbol used to mark the boundary between the integral and the fractional parts of a decimal number
  • hideIdColumn: The argument passed in the function call – true to hide the ID column, false to keep it visible.

Read here how to find the list GUID

Please ask if anything is unclear.

Alexander

Get n’th given day of any month

Based on recent requests i want to post this solution for getting the n’th given day of any month in any year.

For example the third Friday of current month:

&lt;script type=&quot;text/javascript&quot;&gt;
var myDay = getNthDayOfMonth(3,5,'','');
alert(myDay);

/*
Parameters:
index: n'th occurrence of the specified day
day: daynumber - javascript way where sunday is 0 and is saturday is 6
month: javascript way which is 0-11 [optional - defaults to current]
year: Full year - four digits [optional - defaults to current]
*/
function getNthDayOfMonth(index,day,month,year){
// Create date object
var date = new Date();
	// Set to first day of month
	date.setDate(1);
	// If supplied - set the month	
	if(month!==''&amp;&amp;month!==undefined){
		// Set month
		date.setMonth(month);
	}else{
		month = date.getMonth();
	}
	// If supplied - set the year	
	if(year!==''&amp;&amp;year!==undefined){
		// Set year
		date.setFullYear(year);
	}else{
		year = date.getFullYear();
	}
	// Find daynumber
	firstDay = date.getDay();
	// Find first friday.
	while(date.getDay()!=day){		
		date.setDate(date.getDate()+1) ;
	}
	switch(index){
		case 2:
			date.setDate(date.getDate()+7);			
		break;
		case 3:
			date.setDate(date.getDate()+14);				
		break;
		case 4:
			date.setDate(date.getDate()+21);
		break;
		case 5:
			date.setDate(date.getDate()+28);
			if(date.getMonth()!==month){
				date = null;
			}
		break;
	}
	return date;
}
&lt;/script&gt;

Alexander

Poll for SharePoint

March 15, 2015: I have updated this solution. You find v2.0 here.

Please note: The Google Image Charts used in this solution is deprecated and will stop working April 20, 2015.

Change log
January 28. 2014
v1.54 fixes one incompatibility with SP 2013. I have not fully tested this so please let me know if you find any bugs.

July 01. 2013 v1.53: The sort order of answers in chart now reflects the order given in the setup. I have removed some script references so that you now must refer spjs-utility.js – get it here

You must update the CEWP code to include reference to spjs-utility.js

15.12.2011 v1.5.1: Bugfix in the file “PollForSharePoint.js” – line 238. The property “listBaseUrl” were missing – thanks to Jaap Dijkma for finding this bug.


04.12.2011 I have updated the solution to support putting the list in a central location. See “listBaseUrl” below.


22.10.2011 Updated the code to support free input rather than predefined answers – as requested by Claudia:

Hi, thank you for this wonderful piece of code, I think it’s great and we use it on our intranet :).
I wondered if it is possible to use a single line of text for free input instead of radiobuttons with preset answers?
We like to use the poll for ‘brandtagging’ so that people can type keywords.
Just wondering…..
thanks! Claudia

I thought this was a clever idea and have implemented this in v1.4. See updated CEWP code and description below.


17.08.2011 Updated the code with these changes:

  • Lets you view the results and come back to answer.
  • Tidied up the code.
  • The charts now supports https (Thanks to Google).
  • Removed the poll question from the chart title to preserve the formatting.

01.03.2011 Updated the code to fix a bug when “singleResponse” is true. Thanks to “Al”. I have also included two more settings in the “argObj”: qStyle and aStyle. These sets the CSS style of question and answers. See CEWP code below.


28.11.2010 Updated the code to support special characters in the poll question and answers. Thanks to Christophe for the tip.


This code lets you generate polls using JavaScript/jQuery only. No need for server side installed WebParts.

Poll
IMG

Result with column chart
IMG

Result with bar chart
IMG

Result with pie chart
IMG

Result with “table chart”
IMG

Already answered
IMG

Not active
IMG

Finished
IMG

The charts are generated using Google Chart Tools / Image Charts (aka Chart API).


Create a custom list with the following fields

  • Answer: Single line of text
  • Question: Single line of text

Name it anything you like, but keep the display name fairly simple (no special characters) as you will use the display name in the CEWP code.

CEWP code

The CEWP code below refers jQuery from Google. If you have a local copy of jQuery you can change the script src. You find the code for the file “PollForSharePoint.js” at the bottom of the page. In this example the file “PollForSharePoint.js” is placed in a document library named “Javascript”.

NOTE: You must change the script src for the file “PollForSharePoint.js” and “spjs-utility.js” to point your instance of the files – the CEWP code will not work unless you do this.

Place this code where you want the poll to appear:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="/test/English/Javascript/Poll/spjs-utility.js"></script>
<script type="text/javascript" src="/test/English/Javascript/Poll/PollForSharePoint.js"></script>
<script type="text/javascript">

buildQueryWP({pollAnswerListName:'PollA',
				listBaseUrl:L_Menu_BaseUrl,				
				id:'myPoll_01-03-2011', // Allowed characters id a-z, 0-9 - and _
				start:'10/22/2011', // format: mm/dd/yyyy
				end:'11/10/2011', // format: mm/dd/yyyy
				singleResponse:false,
				q:"What is your<br />favorite junk food?",
				qStyle:'font-size:small;font-weight:bold;color:gray',
				aStyle:'font-size:xx-small',
				a:['Pizza','Hot dog','Hamburger','Neither of them'], // Leave empty for free input				
				color:['32CD32','FFCC11','FF3300','C0C0C0'],
				forceLowerCaseAnswer:false, // Group result by lowercase				
				chart:'col', // table, bar, col or pie
				height:100,
				width:450});
</script>

You can control these values in the top of the file “PollForSharePoint.js”:

var submitLinkText = 'Submit';
var backLinkText = 'Back';
var showResultBtnText = 'Show result';
var pollNotActiveText = 'The poll is not active prior to {0}';
var pollEndedText = 'The poll ended on {0}';
var alreadyRespondedText = 'You answered: ';
var totalResponsesLabel = "Total responses: ";

Object attributes explained

  • pollAnswerListName: DisplayName or GUID of the list that stores the answers
  • listBaseUrl: The baseUrl of the site. This is like “/sites/hr” when the list is located in the site “hr” under “/sites”. Use L_Menu_BaseUrl (or omit the property) for current site. New in v1.5
  • id: The unique id of the poll. All poll answers are stored in a list and this id is used to separate each poll
  • start: Start date in the format mm/dd/yyyy
  • end: End date in the format mm/dd/yyyy
  • singleResponse: true for one reply per user, false for unlimited number of replies
  • q: Poll question. To have a linefeed in the question, use <br>
  • qStyle: CSS syntax style
  • aStyle: CSS syntax style
  • a: Answers in an array format. To use free input and not predefined answers, leave the array empty.
  • color: Colors for the chart in an array format. This must have the same length as the previous parameter – one color for each answer
  • forceLowerCaseAnswer: Primarily for use with free input to avoid getting two “series” when the only difference are uppercase characters. New in v1.4
  • chart: “bar” for bar chart, “col” for column chart, “pie” for pie chart or “table” for a plain table.
  • height: Height in pixels
  • width: Width in pixels

Regarding free input
If you leave the attribute “a” as an empty array, the user can supply free text as “answer”. When using free input, the result are automatically presented as a table.

Download code

The code for the file “PollForSharePoint.js”:
Download code from this location

Ask if anything is unclear.

Alexander

Convert a standard SharePoint lookup column to a full blown cross site lookup using javascript only

I have updated the tool described in this article with some new functionality.

The functionality i will describe here is the ability to convert a standard SharePoint lookup column to a cross site lookup column using javascript/jquery only!

Download the script from the above referred article. Create a Lookup column in your list and have it point to the actual list it is created from (it is in fact not relevant what list you point it towards). Load the script from the above described article and select your list:

Images

IMG


Select the list
IMG


Modify the web and list association and hit “Save”:
IMG

NOTE: The web selector is only available for site collection administrators.

If you are a non site collection administrator, you may change the list association, but not the web association.

This method requires NO modification to the field schema and is fully compatible with Data sheet view etc.

I have not had the chance to test it in SharePoint 2010 yet, but i can see no reason why it should not work.

Alexander

Interactive Charts using Google Visualization API v2.0

You find v3 of this tool here


16.08.2011 I have released version 2.9.3. Read about it here


05.06.2011 I have released version 2.9.1. Read about it here


05.05.2011 I have released version 2.8.5. Read about it here


27.03.2011 I have released version 2.8 featuring different filtering methods. Read about it here


*** See bottom of article for change log on older versions ***


Since i posted the previous version of the solution that utilizes the Google Chart Tools / Interactive Charts (aka Visualization API), Google has updated their API and made the previous version more or less obsolete.

NOTE:
I have made a “bridge” between Google’s Visualization API and SharePoint. How the charts render or function it up to Google to decide – it is their “product”. Refer the various configuration options by following the link from the “Edit chart UI”.

Read Google’s terms of Use here.

Google’s Data Policy on this charts
All code and data are processed and rendered in the browser. No data is sent to any server.

This new release features these chart types:

Other modifications made:

  • All code in one file: “ChartUsingGoogleVisualizationAPI.js”
  • In the CEWP: Refer the above file, jQuery (fixed external link) and the Google jsapi (fixed external link)
  • Chart configuration list is automatically created if it is not already present

The solution is tested in IE8, Google Chrome 5.0.375.127 and Firefox 3.6.8.

Some screenshots (from v2.0 – changes introduced in subsequent versions are not reflected her):

Not all chart types are presented.
When first adding a chart CEWP to a site, the configuration list is created:

Press OK:

Gauge – a good KPI:

GeoMap:

Column chart – counting unique values per country:


This chart type merges all “lines” where the country is the same, counting “fruits” in the choice column named “Fruit or vegetable”.

LineChart:

Map:

Motion Chart:



The “date” column can be a SharePoint data-column, or a “US formatted” string (still formatted as “Date in the UI”) in the format “mm/dd/yyyy”. Refer the “Instructions for MotionChart” link in the UI.

Organizational Chart:



This is the data that makes up this chart. Note that it is built with various calculated columns – no need for it to render as HTML in the list – it is “raw data”.

PieChart:

More examples – including custom CAML-queries will be added on request.


The new GUI from v2.6.5 (introduced in v2.5)



The Code:

This is the CEWP code:

&lt;div id=&quot;MyChart1&quot;&gt;&lt;/div&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
/*****************************************************
		Address all containers
*****************************************************/
// All charts must be represented by a container with a unique id. This container  must be present in the page
arrOfChartContainers = [&quot;MyChart1&quot;];
&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;http://www.google.com/jsapi&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/ChartUsingGoogleVisualizationAPI.js&quot;&gt;&lt;/script&gt;
Note the <div id=”MyChart1″></div> This is the chart “placeholder”. To add more charts, add more placeholders and add them to the array “arrOfChartContainers”.

The placeholders can be inserted in other CEWP’s as long as they render before the chart is initiated (place them above the “Chart CEWP”).

It is essential that the scripts tags for “jsapi” and “ChartUsingGoogleVisualizationAPI.js” are placed below the script tag that defines the “arrOfChartContainers”.

The code for the file “ChartUsingGoogleVisualizationAPI.js”:

Download code from this location

This link can contain different “versions”:

  • ChartUsingGoogleVisualizationAPI_vX.Y.Z.js – Uncompressed code
  • ChartUsingGoogleVisualizationAPI_vX.Y.Z-min.js – Minified using YUI Compressor to reduce the file size
  • ChartUsingGoogleVisualizationAPI_vX.Y.Z-packer.js – Compressed/obfuscated using Dean Edward’s Packer to further reduce the file size

You must update the script name in the CEWP to reflect the version number.

Note:

When new versions are released, they will be placed in a folder with the version number as label. Be sure to download the latest version.

If you are using a browser other than IE, right click the file and select “Save link as” or “Save linked content as…”.

Tip:

To make it convenient for end users to use this charting tool, create a few CEWP’s with your favorite setup (1 placeholder, 4 placeholders in a table form and so on). Export the CEWP and upload it to your web part gallery (in the root of the site collection).

You can now add it as a regular webpart from the “web part selector” in edit page mode.

Enjoy!
Alexander


Change log:

27.03.2011 : New features are described here

19.10.2010 v2.7 is released. You find it in the “download section” above This version is the final fix (i hope…) for the web selector problems for non Site Collection Administrators (SCA).

For SCA’s there are no changes, but for those not SCA, I have abandoned my attempt to auto populate a web selector and gone for a input field. The user must write the URL of the web to load the list collection from. The reason for this is the fact that the method “GetAllSubWebCollection” is not accessible to non SCA’s, and that the manual iteration trough all webs caused prompts for credentials as it hit webs the current user did not have access to.

You will still get a credential prompt if you try to load the list collection for a web you have no rights to, but you will not get stuck in a “endless” loop of credential prompts.

New features:
In this version i have added the option to restrict edit access for a individual chart to a specific SharePoint user group. You find this setting in the Advanced option area in the “Edit Chart GUI”:

This is no “real” security setting as it only skips the rendering of the “edit chart button” and does not restrict the edit rights to the chart configuration list. If you want a true security setting you must change the permissions for each “chart” in the configuration list, or the permission for the configuration list itself.

Important!

v2.7 requires you to add one column of type “Single line of text” to the chart configuration list. The name of the field must be exactly “EditAccessGroupID” (without the quotes). Optionally you can delete the configuration list and have the script recreate it. The latter will result in you loosing all your existing chart configurations.


05.10.2010 v2.6.5 unintentionally made it impossible for other than site collection administrators to select web. This update (v2.6.6) fixes this issue. For uses that are not site collection administrators, the loading of the web selector may take a few seconds extra.

The check for edit page rights has been removed due to feedback from users that had problems editing charts. To restrict editing of the charts, manage user right for the configuration list – all users must have at least read access!

28.09.2010 Still some issues with the web selector as the v2.6.5 unintentionally made it impossible for other than site collection administrators to select web. I’m working on an updated version that will fix this. In the meantime, use v2.6.4 if you are not on a managed path…

23.09.2010 A new release (v2.6.5) has been added to the download section. This intends to fix the empty web selector for users with site collection on a managed path.

22.09.2010 There are some unresolved issues with the current release. You can follow the progress in the comment section below.

19.09.2010 A new version (2.6.1) is added to the “download section” – see bottom of article. It features enhanced functionality for selecting web. It now let you pick freely from all sites within the site collection (siblings, parent sites and subsites). This version may contain bugs, so please let me know if you find any.

14.09.2010 Small update to the code to fix the “Initial state” in motion charts, as well as some minor bug fixes. I have moved the files to my home server for you to download. This provides a better solution then manually highlighting and saving 2000+ lines of code. Please note that the file now come in three different “versions”. Read more in the “download section” below.

09.09.2010 Small update to the description regarding update from v2.0 to v2.5. I forgot to mention another field required to be added to the Chart configuration list: ListBaseUrl. This in addition to the already mentioned “ChartFormatters”. I have also removed an alert that was left in the code (line 40).

Christophe notified me of a problem with the 2010 compatibility in sub-site “homepage” – which is a wiki page. The CEWP HTML handling in SP2010 is a bit “different” than in SP2007. When editing the HTML source code, it actually pulls the contents generated by the script into the edit dialog and does not use the content that was originally saved to the CEWP… This is a bit of a headache!. A workaround for the wiki-pages is to use the “Content Link” property for the CEWP and link to a .txt file with the CEWP code placed in a document library (alongside the other scripts).

06.09.2010 Updated the script “ChartUsingGoogleVisualizationAPI.js” and the CEWP code. The version number is notched up to 2.5 and the changes are:

  • Added the ability to chart data from all ascending parent sites and all first level subwebs of current site
  • Added a few formatter options in the UI – refer the linked resources for instructions (thanks to Paulo for the tip).
  • Added new “action” for formatting as % (value*100).
  • The solution is now SharePoint 2010 compatible
  • Enhanced the UI for editing charts – all options and columns are now directly editable.
  • No more need to specify the “userListGuid” and the “userListBaseUrl” in the CEWP code.
  • The naming of the charts in the Chart Configuration list is enhanced – it now prefixes the chartId with “location.pathname” to prevent overwriting an existing chart when reusing the CEWP code in another page (thanks to Christophe for the tip).
  • Edit chart is now done in the standard “Browse mode” and not in “EditPage mode”. The edit button is found in the top left corner of the chart. The button is only visible for users with “Edit page rights” and does not show on printouts.
  • And more…

Note: This update introduces two new columns in the configuration list (GoogleVisualization_InteractiveChartsConfig). To reuse the existing Chart configuration list you must add one field of type “Multiple lines of text (Plain text) named “ChartFormatters” and one field of type “Single line of text” named “ListBaseUrl”. Optionally you can delete the Configuration list and have this solution automatically recreate it for you.

Please note that the CEWP code has changed alongside the code for the file “ChartUsingGoogleVisualizationAPI.js”.

Note about existing charts:
All your existing charts will need to be updated with the new “page id” in the chart configuration list (GoogleVisualization_InteractiveChartsConfig). Look at the new configuration item that is automatically added – copy it’s name and update your existing chart configuration – while deleting the newly added (empty) chart configuration.

27.08.2010 Small update to the file “ChartUsingGoogleVisualizationAPI.js” to fix a formatting issue when using object literal notation in the chart options.

List all attachments when clicking the paperclip in a list view

Change log:

07.10.2011 A new version is published – you find it here.

23.09.2010 Moved the code to a server for direct download to make it easier for the users. You find the link below. The current stable version is 1.5.

13.09.2010 Fixed bug when ID column was not placed to the far right.

07.09.2010 Fixed bug when list view was not the topmost webpart.

30.08.2010 Added “one click open” if only one attachment is found.


I got this request from Chris:

…the challenge I’m currently trying to solve is to get the attachments paperclip in a listview clickable. Using a doclib and linking against the file is not an option since we are talking about a lot of files with the same name which should be stored with the list entry (one file per entry).

There’s a solution from Paul Grenier at EUSP, but that doesn’t work for large collections, so it’s not usable.

I thought of setting up the path ‘manually’, and displaying this entry, since I noticed that the attachment path is always like URL/site/lists/listname/attachments/list_item_id/filename. Though I might be able to come up with all the details up to the ID I have no idea on how to get the filename automatically.

Can you think of any other way to make the paperclip clickable to open the attachment?

Thanks,
Chris


Here we go:

This method uses the webservice lists.asmx and the operation GetAttachmentCollection.

It is tested in IE8, Chrome 5.0 and Firefox 3.6.8 in WSS3.0. It works in both standard list views, and grouped views.

It has briefly been tested in SP2010, but is only partially compatible (minor issue with the click on the paperclip selecting the row, and it only works in non-grouped views).

The only requirement for this solution to work is the ID column being in the view – it can be hidden by setting the variable hideIdColumn = true (default).

The CEWP code

&lt;script src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;/test/English/Javascript/previewAttachmentsOnClick.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;

   hideIdColumn = true;
   customListAttachments();

&lt;/script&gt;

Place the CEWP below the list view!

Download the file “previewAttachmentsOnClick.js” from this location

Note:

When new versions are released, they will be placed in a folder with the version number as label. Be sure to download the latest version.

If you are using a browser other than IE, right click the file and select “Save link as” or “Save linked content as…”.

As if anything is unclear.

Alexander

Vertical Scrolling WebPart

15.07.2010 Updated the code for the file “VerticalScrollingWebPart.js” to try to fix the overflow issue in IE6.

24.06.2010 The code for the file “VerticalScrollingWebPart.js” is updated. I actually forgot to update it as i made some adjustments in the CEWP code… I hope the overflow issue is fixed with this update.

I got this request from Charlie:

…a solution that I can use as a dashboard web part to vertically scroll the most recent “top 10” items from a 2nd list?

Example: I need to be able to grab the most recently items marked as “Completed” or “Sold” from a list and be able to show 2-3 fields in the scroller.

Click here for a crude example – the scrolling is not so choppy – this is only a animated gif to give you a hint of how the solution works.

The scrolling action pauses when hovered with the mouse.

As always we start like this:
Create a document library to hold your scripts (or a folder on the root created in SharePoint Designer). In this example i have made a document library with a relative URL of “/test/English/Javascript” (a sub site named “test” with a sub site named “English” with a document library named “Javascript”):
IMG

The jQuery-library is found here. The pictures and the sourcecode refers to jquery-1.4.2.min. Update the script “src” if you use another version.

The sourcecode for the file “VerticalScrollingWebPart.js” is provided below.

Add this code to a CEWP where you want the scrollable contents to appear:

<script type="text/javascript" src="/test/English/Javascript/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="/test/English/Javascript/VerticalScrollingWebPart.js"></script>
<script type="text/javascript">
init_fillScrollableDiv({'listGuid':'A4B4E15A-C5B0-47BC-A08B-739CD48FE58A',
	'listBaseUrl':'/test/English',
	'listViewGuid':'5BD378F4-25D5-4880-9C5B-1667FE43978D',											
	'viewFields':['Title','MultiLine'],
	'viewFieldsStyle':['font-weight:bold','padding:0 0 0 5'],	
	'divID':'myScrollableDiv',
	'divHeight':'250px',
	'divWidth':'500px',	
	'speed':4,
	'linkBack':true});
</script>

Read here how to find the FieldInternalNames for your fields and the “listGuid” or “listViewGuid” for your list.

Parameters explained:

  • listGuid: GUID of the source-list
  • listBaseUrl: Relative URL to site/subsite. If root site use only two quotes representing a blank string – like this: “”.
  • listViewGuid: GUID of the view to use from the source-list – if left empty it uses the default view.
  • viewFields: Array of FieldInternalNames to use in the scrolling webpart.
  • viewFieldsStyle: Array of styles to match the array of FieldInternalNames above.
  • divID: The ID of the scrollable DIV. Can be anything as long as it is unique on the page.
  • divHeight: The hight of the scrollable area.
  • divWidth: The width of the scrollable area.
  • speed: A number representing the scroll speed.
  • linkBack: If set to true it adds a link to open the item clicked on.

The sourcecode for the file “VerticalScrollingWebPart.js”:

/* Pulls items from a list view and presents them as a Vertical Scrolling Web Part
 * ---------------------------------------------
 * Created by Alexander Bautz
 * alexander.bautz@gmail.com
 * https://spjsblog.com
 * Copyright (c) 2009-2010 Alexander Bautz (Licensed under the MIT X11 License)
 * v1.2
 * LastMod: 14.07.2010
 	- LastChange: 23.12.2014 - fixed a jQuery incompatibility issue for newer jQuery versions. Please note that the code is still old and not the best of quality.
 * ---------------------------------------------
 * Include reference to:
 *  jquery - http://jquery.com
 *	VerticalScrollingWebPart.js (this file)
 * ---------------------------------------------
*/

function init_fillScrollableDiv(obj){
	// Build the div
	var myDivBuffer = [];
	myDivBuffer.push("<div style='vertical-align:top;position:relative;overflow:hidden;cursor:default;height:"+obj.divHeight+";width:"+obj.divWidth+"'>");
	myDivBuffer.push("<div id='"+obj.divID+"' style='position:relative'></div>");
	myDivBuffer.push("</div>");
	myDivContainer=myDivBuffer.join('');	
	document.write(myDivContainer);
	$(document).ready(function(){
		fillScrollableDiv(obj)
	});
}

function fillScrollableDiv(info){
	wsBaseUrl = info.listBaseUrl + '/_vti_bin/';
	info.animBegin = 0;
	info.animPart = 0;
	// Query the list for items	
	var res = queryItemsByViewName(info.listGuid,info.listViewGuid,info.viewFields.concat('ID','FileDirRef'));
	if(res.count==-1)alert("An error occured - check the parameters \"listGuid\", \"listBaseUrl\" and \"listViewGuid\".");
	var finalBuffer = [];
	var path = '';
	$.each(res.items,function(i,item){
		var partBuffer = [];
		if(path==''){
			var pathRaw = item['FileDirRef'];
			path = "/"+pathRaw.substring(pathRaw.indexOf(';#')+2);
		}	
		$.each(info.viewFields,function(idx,fin){
			var style = '';
			var thisVal = (item[fin]==null)?'':item[fin];
			if(thisVal.indexOf(';#')>-1){
				thisVal = thisVal.substring(thisVal.indexOf(';#')+2);
			}			
			if(info.viewFieldsStyle[idx]!=undefined){
				style = " style='"+info.viewFieldsStyle[idx]+"'";
			}
			partBuffer.push("<tr><td"+style+">"+thisVal+"</td></tr>");	
		});		
		finalBuffer.push("<hr style='height:1px;color:black' />");
		if(info.linkBack){
			finalBuffer.push("<table title='Go to item' style='cursor:pointer' ");
			finalBuffer.push("onclick='javascript:location.href=\""+path+"/DispForm.aspx?ID="+item['ID']+"&Source="+location.href+"\"' ");
			finalBuffer.push("cellspacing='0' cellpadding='0'>"+partBuffer.join('')+"</table>");
		}else{
			finalBuffer.push("<table cellspacing='0' cellpadding='0'>"+partBuffer.join('')+"</table>");
		}	
	});
	var myContents = finalBuffer.join('');
	// Update the content in the scrollable div
	$("#"+info.divID).html(myContents)
		.mouseenter(function(){			
			var now = new Date();
			info.animPart += (now-info.animBegin);		
			$(this).stop();
		})
		.mouseleave(function(){		
			$(this).stop();
			var partScr = parseInt($(this).css('top'));
			scrollMyDiv(partScr,info);
		});
	// Call scroll function
	scrollMyDiv('',info);
}

function scrollMyDiv(scroll,info){
	info.animBegin = new Date();
	var myDiv = $("#"+info.divID);
	var ch = myDiv.height();
	var chpHeight = myDiv.parent().height();	
	if(scroll==''){
		var scroll=chpHeight;
	}
	var duration = (ch*(info.speed*10))-info.animPart;
	myDiv.css({'top':scroll}).animate({"top":-ch},duration,'linear',function(){
		info.animPart = 0;
		scrollMyDiv('',info);
	});
}

// http://www.steveworkman.com/html5-2/javascript/2011/improving-javascript-xml-node-finding-performance-by-2000/
$.fn.filterNode = function(name) {
	return this.find('*').filter(function() {
		return this.nodeName === name;
	});
};

// Function to pull items from view
function queryItemsByViewName(listName, viewName, viewFields, pagingInfo){
	var content = buildQueryContentByViewName(listName, viewName, viewFields, pagingInfo);
	var result = {count:-1, nextPagingInfo:'', items:[]};
	wrapSoapRequest(wsBaseUrl + 'lists.asmx', 'http://schemas.microsoft.com/sharepoint/soap/GetListItems', content, function(data){
		result.count = parseInt($(data).filterNode("rs:data").attr('ItemCount'),10);
		result.nextPagingInfo = $(data).filterNode("rs:data").attr('ListItemCollectionPositionNext');
		$(data).filterNode('z:row').each(function(idx, itemData){
			var fieldValObj = {}
			$.each(viewFields,function(i,field){
				var value = $(itemData).attr('ows_' + field);
				if(value == undefined) value = null;
				fieldValObj[field]=value;
			});	
			result.items.push(fieldValObj);		
		});
	});
	return result;
}

function buildQueryContentByViewName(listName, viewName, viewFields, pagingInfo){
	var result = [];
	result.push('<GetListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">');
	result.push('<listName>' + listName + '</listName>');
	result.push('<viewName>' + viewName + '</viewName>');
	if(viewFields != null && viewFields.length > 0){
		result.push('<viewFields><ViewFields xmlns="">');
		$.each(viewFields, function(idx, field){
			result.push('<FieldRef Name="' + field + '"/>');
		});
		result.push('</ViewFields></viewFields>');
	}
	result.push('<queryOptions><QueryOptions xmlns=""><IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns>');
	if(pagingInfo != undefined && pagingInfo != null && pagingInfo != '')
		result.push('<Paging ListItemCollectionPositionNext="' + pagingInfo.replace(/&/g, '&') + '" />');
	result.push('</QueryOptions></queryOptions>');
	result.push('</GetListItems>');
	return result.join('');
}

function wrapSoapRequest(webserviceUrl,requestHeader,soapBody,successFunc){
	var xmlWrap = [];
		xmlWrap.push("<?xml version='1.0' encoding='utf-8'?>");
		xmlWrap.push("<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>");
		xmlWrap.push("<soap:Body>");
		xmlWrap.push(soapBody);
		xmlWrap.push("</soap:Body>");
		xmlWrap.push("</soap:Envelope>");
		xmlWrap = xmlWrap.join('');
	$.ajax({
		async:false,
		type:"POST",
		url:webserviceUrl,
		contentType:"text/xml; charset=utf-8",
		processData:false,
		data:xmlWrap,
		dataType:"xml",
		beforeSend:function(xhr){
			xhr.setRequestHeader('SOAPAction',requestHeader);
		},
		success:successFunc
	});
}

Save as “VerticalScrollingWebPart.js” – mind the file extension – and upload to the scriplibrary as shown above.

Ask if anything is unclear!
Alexander

Send email with javascript – with the help of a workflow in a dedicated “send email-list”

This solution “injects” data, using JavaScript, into a custom list. This list has one purpose only: sending an email containing the injected data.

The custom list have the following fields:

  • Title: The native Title field – holds the subject.
  • To: Single line of text.
  • Cc: Single line of text.
  • EmailBody: Multiple lines of plain text.

IMG

With a workflow like this:
IMG
IMG
IMG
IMG
IMG
You could skip the part with “Store …. in Variable” for “To” and “Cc” if you like, this step was originally used for pulling values from a multi select people picker. This field cannot be used in “To” or “Cc” without this procedure.

As always we start like this:
Create a document library to hold your scripts (or a folder on the root created in SharePoint Designer). In this example i have made a document library with a relative URL of “/test/English/Javascript” (a sub site named “test” with a sub site named “English” with a document library named “Javascript”):
IMG

The jQuery-library is found here. The pictures and the sourcecode refers to jquery-1.4.2.min. If you use another version, remember to update the script “src”.

The scripts “interaction.js” and “stringBuffer.js” are created by Erucy and published on CodePlex.

Read here how to add a CEWP to the NewForm or EditForm, how to find the list Guid of your list, and how to find the FieldInternalName of your columns.

Add this code to a CEWP – update the script “src”:

&lt;input type=&quot;button&quot; onclick=&quot;javascript:init_sendMailWithJavascript()&quot; value=&quot;Send test-mail&quot;&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;../../Javascript/jquery-1.4.2.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;../../Javascript/interaction.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;../../Javascript/stringBuffer.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;

var sendMailListGuid = '{68CC0B80-7013-41B2-B591-CBA3899B713D}';

function init_sendMailWithJavascript(){
	sendMailWithJavascript(&quot;My custom subject&quot;,&quot;to@mail.com&quot;,&quot;cc@mail.com&quot;,&quot;&lt;div&gt;This is a div&lt;/div&gt;&lt;a href='https://spjsblog.com'&gt;SharePoint JavaScripts&lt;/a&gt;&quot;);
}

function sendMailWithJavascript(Subject,To,Cc,Body){
	wsBaseUrl = L_Menu_BaseUrl + '/_vti_bin/';
	var res = addItem(sendMailListGuid,{Title:Subject,To:To,Cc:Cc,EmailBody:Body});
	if(!res.success){
		alert(res.errorText);
	}else{
		alert(&quot;Sending OK!&quot;);
	}
}
&lt;/script&gt;

This code inserts a button that calls the function “init_sendMailWithJavascript” and sends a test message. You must modify the variable “sendMailListGuid” to reflect your “send mail” list’s GUID. Refer to the link above the codeblock for instructions. Also modify the “To” and “Cc” addresses.

The function “init_sendMailWithJavascript” is just an example – you can call the function “sendMailWithJavascript” directly from your script.

NOTE: Starting Workflows is not possible for anonymous users (may be possible using a third party fix).

Ask if anything is unclear.

Alexander