Tag Archives: Javascript

Nagios – Improve User Experience with SSI and Javascript

Hello everyone, today I want to show you a little improvement I found for this previous post. (Btw This post has the same prerequisites. So have a look at my posts Nagios – Use UTC and Nagios – Change date format too.) The problem with my previous solution was that you needed either Google Chrome or Mozilla Firefox with the Tampermonkey/Greasemonkey plugin to make it work. (And it would not work in Internet Explorer) And you needed to do this for every user who wanted this solution.

Ok. So here is the new solution. We will edit the Nagios web interface so that it will show date and time values in relative time on all browsers for all users.

Ok. Let´s get down to business 🙂 (Btw I did this on Ubuntu 14.04.2)

Prerequisites:

You need to download the following scripts first to make my RelativeTime.js Script work:

Now create a new folder in “/usr/local/nagios/share/js” to store your custom Javascript files: (I called mine custom)

sudo mkdir /usr/local/nagios/share/js/custom

Place moment.js and wgxpath.install.js into your “custom” folder.

And add the following script to your “custom” folder:

<code>function ConvertToRelativeTime()
{
wgxpath.install();
textNodes = document.evaluate("//text()", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);

var regexString = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
var searchRE = new RegExp(regexString);

for(var i=0;i<textNodes.snapshotLength;i++)
{
var node = textNodes.snapshotItem(i);
node.data = node.data.replace(searchRE, moment.utc(node.data).fromNow());
}
}

document.addEventListener("DOMContentLoaded", function(event){
ConvertToRelativeTime();
});
</code>

(Remove the

<code>

and

</code>

tag.)

The script will look for UTC ISO8601 date time values and will replace them with relative date time values. Ok. Now go to “/usr/local/nagios/share/ssi” and create a new file called “common-header.ssi“. (If you create a file called “common-header.ssi” or “common-footer.ssi” it will add a header or footer to all cgi files. If for example you create a file called “status-header.ssi” it will add a header to the status.cgi file. Example here: http://nagios.fm4dd.com/pnp4nagios/docs/view/en_US/webfe)

<code><script type="text/javascript" src="/nagios/js/custom/moment.js"></script>
<script type="text/javascript" src="/nagios/js/custom/wgxpath.install.js"></script>
<script type="text/javascript" src="/nagios/js/custom/RelativeTime.js"></script>
</code>

(Remove the

<code>

and

</code>

tag.)

Now run the following commands to restart the Apache webserver and the Nagios service to apply the changes:

sudo service apache2 restart
sudo service nagios restart

Here is a picture how your web interface will look before you apply the script:

nagios_before_ssi

Here is a picture how your web interface will look after you applied the script:

nagios_after_ssi

And here is a picture after you applied the script in Internet Explorer:

nagios_after_ssi_internet_explorer

Here is some important information how I made my script work in Internet Explorer:

Important:

If you are using Internet Explorer please keep in mind that “XPathResult” will not work without solutions like “Wicked Good XPath“. And make sure that you are not using Internet Explorers Compatibility Mode otherwise the “DOMContentLoaded” function I use in my RelativeTime.js script will not work.

xpathresult_undefined_internet_explorer

internet_explorer_compatibility_mode

Well, that´s it. Now Nagios should display all date time values in relative time. I hope you liked my post and I hope to see you again next time 🙂

As always you can download my code from here.

Sources:

http://nagiosbook.org/html/ch13s02.html

http://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery

http://stackoverflow.com/questions/23560438/xpathresult-is-undefined-in-ie11

http://stackoverflow.com/questions/15743049/xpath-incompatible-with-internet-explorer

https://github.com/google/wicked-good-xpath

http://google-opensource.blogspot.co.at/2012/09/wicked-good-xpath-faster-javascript.html

http://iswwwup.com/t/393167235ec7/javascript-wicked-good-xpath-evaluate-xpathresult-contains.html

http://nagios.fm4dd.com/pnp4nagios/docs/view/en_US/webfe

Advertisements
Tagged

Nagios – Improve User Experience with Tampermonkey/Greasemonkey

Hello everyone, in these last few posts: Nagios – Change date format and Nagios – Use UTC I showed you how you can alter the date format and timezone of your Nagios server. Today I want to show you how you can improve User Experience with a simple Greasemonkey/Tampermonkey script by converting all date time values into relative time values (as seen on Facebook or used by SharePoint).

Important: If you want to use the below script without altering the “regexString” value you will need to follow this post of mine to make Nagios use the ISO8601 date format. And you need to follow this post to make Nagios use UTC.

Ok. Let´s get down to business 🙂

If you use Firefox install the Greasemonkey plugin or if you use Google Chrome install the Tampermonkey plugin to run the below script (If you use Internet Explorer you are unfortunately out of luck because neither Greasemonkey nor Tampermonkey are available for it to my knowledge). And here is the script:


// ==UserScript==
// @name Nagios - Date time to relative time
// @namespace https://theezitguy.wordpress.com/
// @version 1.0
// @description This script will turn every date time value into a relative time value (e.g. it will turn "2014-07-21 00:00:00" into "a year ago").
// @author theezitguy
// @match http://10.0.0.3/nagios/*
// @grant none
// @require http://momentjs.com/downloads/moment.js
// ==/UserScript==

//Get all textNodes of the website
textNodes = document.evaluate("//text()", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);

//Regex String - Search for date time values in ISO8601 format
var regexString = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
var searchRE = new RegExp(regexString);

//Go through all textNodes and replace date time values with relative time values
for (var i=0;i<textNodes.snapshotLength;i++)
{
var node = textNodes.snapshotItem(i);
node.data = node.data.replace(searchRE, moment.utc(node.data).fromNow());
}

The script will do the following:

It will go through every text node on the website and replace all date time values with relative time values.

Important: You need to alter the “@match” value to point to your Nagios server website before you can use it.

Here is a screenshot before I applied my script:

nagios_without_script_utc_time

And here is a screenshot after I applied my script:

nagios_with_script_relative_time

Well, that´s it. You can now easier read your data on your Nagios web interface.

Not bad, right? I hope you liked my today´s post and I hope to see you again next time 🙂

Sources:

http://momentjs.com/

http://forum.imerx.net/viewtopic.php?f=17&t=262&start=15

http://tuxradar.com/content/greasemonkey-beginners

http://www.digitoffee.com/programming/get-local-time-utc-using-moment-js/94/

Tagged

Tampermonkey – Youtube URL Rewrite Script

Hello everyone. Welcome to my first post of the year. Like last year I will try my best to share useful information with you. So here we go:

I think everyone of us got annoyed by age restricted videos at least once in our life and saw a screen like this which told us to log in:

youtube_age_restriction

(Sorry for the german screenshot.) Since I do not want to log in to watch a restricted video I tried to come up with a solution. Some of you might know this trick here. The trick is simple. Replace “watch?v=” with “v/” to circumvent the age restriction check. Not too much work but I wanted something better.

So I decided to use Tampermonkey, an extension for Google Chrome, to add custom Javascripts to websites to alter them. Here is a screenshot of the Tampermonkey Dashboard: (If you are using Firefox you can use Greasemonkey . The same script will also work in Greasemonkey.)

tampermonkey_dashboard

And here is my script which will do the work for me:


// ==UserScript==
// @name Youtube URL Rewrite Script
// @namespace https://theezitguy.wordpress.com/
// @version 1.0
// @description This script will rewrite Youtube URLs when pasted into the address bar of the browser or when the page is refreshed to unblock age restricted videos without the need to log in.
// @author theezitguy
// @include *://www.youtube.com/watch?v=*
// @grant none
// ==/UserScript==

var current_url = document.location;
var video_id = current_url.search.split('v=')[1];
var new_url = "https://www.youtube.com/v/" + video_id;
location.replace(new_url);

The script does the following: When you paste a Youtube Video Link into your address bar it will rewrite the URL. However if you click on a video on Youtube the script will only be triggered if you reload the page. Not perfect but I didn´t find a solution for this. (If you know a solution for this I would be grateful if you could post it in the comments section.)

If you want to try out the script here is a SFW video:

https://www.youtube.com/watch?v=6LZM3_wp2ps

youtube_disabled_age_restriction

That´s it. Now you can use this script to watch age restricted videos without to log in to Youtube or to alter the URL manually. I hope you liked my today´s post and I hope you can use this knowledge to improve your web experience with your own scripts. I hope to see you again next time 🙂

Sources:

https://gist.github.com/hussainm/5345bbefd35e2ec31793

http://andylangton.co.uk/blog/development/javascript-redirect-scripts

https://chrome.google.com/webstore/detail/tampermonkey/dhdgffkkebhmkfjojejmpbldmpobfkfo?hl=en

http://lifehacker.com/watch-age-restricted-youtube-videos-without-signing-in-1529667193

Tagged

SharePoint – Use JQuery to highlight rows

Hello everyone. Today I want to show you how you can use jQuery and SPServices to conditionally highlight rows of your SharePoint Web Parts.

Here is the script you need:

<script type="text/javascript" src="/sites/test2/Script/jquery.min.js"></script>
<script type="text/javascript" src="/sites/test2/Script/jquery.SPServices.min.js"></script>

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

$(document).ready(function() {
$().SPServices({
operation: "GetListItems",
async: false,
listName: "Test",
CAMLQuery: "<Query><Where><Eq><FieldRef Name='YesNoField' /><Value Type='Integer'>1</Value></Eq></Where></Query>",
CAMLViewFields: "<ViewFields> <FieldRef Name='ID' /> </ViewFields>",
completefunc: function (xData, Status) {
$(xData.responseXML).SPFilterNode("z:row").each(function() {

$("tr[iid*='"+ $(this).attr("ows_ID").toString() + "']").css("background-color", "#A3F02E");

});
}
});
});

</script>

The above Script will check the value of the “YesNoField” column in your “Test” List and if the value is “Yes” (1) it will highlight the row. If the value is “No” (0) it will do nothing.

To use the script click on Edit Page on your website and add your List Web Part and a Content Editor Web Part and add a link to your script to the Content Editor Web Part. (You need to store the script somewhere on your website in a Library.)

sharepoint_setup_highlighted_row

If you set up everything correctly the result will look like this:

sharepoint_highlighted_row

That´s it. You can now use this method to highlight specific rows. I hope you liked my post. See you next time 🙂

And as always you can download my script from here.

Sources:

http://mekalikot.blogspot.co.at/2014/01/highlight-sharepoint-task-list-row.html

http://spservices.codeplex.com/wikipage?title=GetListItems

http://social.msdn.microsoft.com/Forums/sharepoint/en-US/1905cd40-c66b-4865-a036-299c88b8bc51/how-to-write-caml-query-for-yes-no-field

http://mekalikot.blogspot.co.at/2014/07/highlight-row-change-font-color-and.html

Tagged ,

SharePoint – Use JQuery to hide columns based on a Users Group Membership

Hello everyone. Today I want to show you how you can use jQuery and SPServices to hide SharePoint columns based on a users group membership.

In a previous post I explained how you can use jQuery and SPServices to Auto-Fill fields. Please follow the instructions in this post but use the script below instead in your NewForm.aspx and/or EditForm.aspx pages.


<script type="text/javascript" src="/sites/test/Script/jquery.min.js"></script>
<script type="text/javascript" src="/sites/test/Script/jquery.SPServices.min.js"></script>

<script language="javascript" type="text/javascript">
$(document).ready(function()
{
$().SPServices({
operation: "GetGroupCollectionFromUser",
userLoginName: $().SPServices.SPGetCurrentUser(),
async: false,
completefunc: function (xData, Status) {
var xml = xData.responseXML.xml;
if(xml.search('SharePoint Group') != -1)
{

$('nobr:contains("TestColumn")').closest('tr').hide();

}
}
});
});
</script>

Replace “TestColumn” with the Name of your column you want to hide. And replace “SharePoint Group” with the Name of your SharePoint Group. If you configured everything correctly your column will be hidden for members of the SharePoint Group you defined in the script. (To hide a column for everyone except a specific group replace

if(xml.search('SharePoint Group') != -1)

with

if(xml.search('SharePoint Group') == -1)

)

That´s it. Now you are able to hide columns from specific user groups. I hope you liked my post. See you next time 🙂

And as always you can download my script from here.

Sources:

http://www.sharepointnadeem.com/2011/09/hide-sharepoint-list-field-based-on.html

http://sharepointroot.com/2011/09/23/sharepoint-2010-how-to-hide-blog-fields-using-jquery/

https://theezitguy.wordpress.com/2014/05/26/sharepoint-auto-fill-fields-using-jquery-and-spservices/

Tagged ,

SharePoint – Use JQuery to set Column Width

Hello everyone. Today I was asked to alter the column width of some SharePoint Web Parts to improve the look and feel of a site. I altered the column width with a simple Javascript and JQuery.

Here is an example how the Web Parts of the site looked before I added my script:

sharepoint_before_column_width_script

Not pretty but luckily there is a simple way to change that.

Here is the script code:

<script src="/sites/test/Scripts/jquery.min.js"></script>
<script language="javascript">
$(function(){
$("TH.ms-vh2:contains('Name')").css("width", "300px");
});
</script>

With the above script you can alter the width of any column you want. You simply need to replace “Name” in the script with the Display Name of your Column.

To use the script you need to add a Content Editor Web Part to your site and embed your script in it.

sharepoint_add_column_width_script

After you have applied your script to the site your site will look like this:

sharepoint_after_column_width_script

Looks better than before, right? Well, that´s it. That´s all you need to do. I hope you liked my post. See you next time.

Sources:

http://social.technet.microsoft.com/Forums/sharepoint/en-US/eab8a3ca-1a91-45ca-b7d5-a5f78592083e/adjust-column-width-in-sharepoint-2013?forum=sharepointgeneral

http://www.emmielewis.com/changesplistcolumnwidth/

Tagged ,

SharePoint – Use Delegate Control to deploy scripts to all pages

Hello everyone. Recently I was searching for an easy way to add scripts to all pages in a SharePoint Site Collection. Mostly because I wanted to find an easy way to add jQuery and SPServices to the pages where I need them with an easy way to deploy new versions and without editing the Master Page of my SharePoint websites. And I think I found a good solution called SharePoint Delegate Control. All you need for this solution is Visual Studio installed on a SharePoint Development Server and you are ready to go.

The first step is to open up Visual Studio to create a new project.

visual_studio_2010_start

Now create a new Empty SharePoint Project.

visual_studio_2010_empty_sharepoint_project

Choose Deploy as a farm solution for your project. This way your solution will be deployed in your entire farm and you can use it in every Web Application when you need it.

visual_studio_deploy_farm_solution

Now we need to add some new items to our project.

visual_studio_2010_add_new_item

First create a new User Control item. I called mine “jQueryAndSPServicesControl.ascx”.

visual_studio_2010_add_user_control

Next create a new Empty Element. I called mine “Elements.xml”.

visual_studio_2010_add_empty_element

Next step: Map SharePoint “Layouts” folder to your project to store your scripts.

visual_studio_2010_add_layouts_folder

Here is an example structure of the Layouts folder from my project:

sharepoint_layouts_folder_structure

Store your scripts by pasting them into your folder structure.

Now we will add our scripts into our User Control.

visual_studio_2010_user_control_custom_scripts

Here is the code from my “jQueryAndSPServicesControl.ascx” User Control:

...
<script type="text/javascript" src="/_layouts/AddSPServicesSolution/jQuery/jQuery.min.js"></script>
<script type="text/javascript" src="/_layouts/AddSPServicesSolution/jQuery.SPServices/jQuery.SPServices.js"></script>
<script type="text/javascript" src="/_layouts/AddSPServicesSolution/jQuery.SPServices/jQuery.SPServices.min.js"></script>

Now we need to add our User Control to our Elements.xml file.

visual_studio_2010_elements_custom

Here is the code from my “Elements.xml” XML file:

<?xml version="1.0" encoding="UTF-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Control ControlSrc="~/_CONTROLTEMPLATES/AddSPServicesSolution/jQueryAndSPServicesControl.ascx" Sequence="90" Id="AdditionalPageHead"/>
</Elements>

After that you need to configure your feature settings. Enter a Title and a Description for your feature and choose a Scope. I chose Site since I wanted my feature to deploy my scripts in the entire Site Collection when I activate it.

visual_studio_2010_feature_scope

After you finished all of the above steps you are ready to go. Start the Debug process to deploy your solution to test it.

When you have a look at your Site Collection features (when you chose Site as a Scope for your feature like I did) you will see that your feature is listed and activated.

sharepoint_site_collection_features_custom

Now go to a page in your SharePoint Site Collection and have a look at its source code. You will see that your scripts have been successfully added to your pages source code. (If you retract your solution, for example by stopping the Debug process, your scripts will be retracted from your pages as well.)

sharepoint_page_source_active_feature

I used an example script to show you what happens when you activate and deactivate your solution in your Site Collection.

Here is the code of my example script:

<script language="javascript" type="text/javascript">
$(document).ready(function() {
$().SPServices({
operation: "GetListItems",
async: false,
listName: "City",
CAMLViewFields: "<ViewFields><FieldRef Name='Title' /></ViewFields>",
completefunc: function (xData, Status) {
$(xData.responseXML).SPFilterNode("z:row").each(function() {
var liHtml = "<li>" + $(this).attr("ows_Title") + "</li>";
$("#tasksUL").append(liHtml);
});
}
});
});
</script>
<ul id="tasksUL"/>

My example script will simply get all items from a List called “City” and display them as a Bulleted List.

The below screenshot shows what my script will do when our custom feature is activated.

sharepoint_delegate_control_feature_activated

The next screenshot shows what happens when you deactivate our custom feature.

sharepoint_delegate_control_feature_deactivated

As you can see nothing bad happens to your page or Site Collection. Your scripts will just stop working.

That´s it. Like that you can deploy your own scripts to your Site Collections in a pretty simple manner. I hope you liked my post and I hope it was useful for you. If you liked my post and want the source code you can download my project from here.

Sources:

http://www.jbmurphy.com/2012/07/03/how-to-add-custom-javascript-code-to-all-sharepoint-2010-pages-delegatecontrol/

http://howtosharepoint.blogspot.co.at/2009/11/include-jquery-file-to-sharepoint.html

http://styledpoint.com/blog/inject-your-jquery-javascript-into-sharepoint-2010-without-modifying-any-master-page-page-layout-or-using-a-web-part/

http://blogs.msdn.com/b/kaevans/archive/2011/04/06/adding-jquery-to-every-page-in-sharepoint-with-delegate-controls.aspx

http://spservices.codeplex.com/wikipage?title=GetListItems

Tagged ,

SharePoint – Create your own Slider Webpart

Hello everyone. A while ago I tried to find a way to create a Slider Webpart. Something that would just slide through a bunch of Pictures containing some messages or news or something like that. And I found a solution.

To create your own Slider Webpart you need the following things:

When you have downloaded these Scripts we can create the Slider Webpart.

For my example I created a Picture Library called “Picture” to store my Pictures I want to use for my Slider Webpart. (I used some banner pictures I found online.)

sharepoint_slider_webpart_picture_Library

The next step was to create a Custom List called “Slider” containing a Multiple lines of text column called “HTML”. Use the “HTML” column to add some messages to your pictures of your Slider. (For my example I just entered a few empty lines because this determines the height of the picture on your Slider Webpart. If you don´t enter something you won´t be able to see your pictures in your Slider. If you add to much text to the HTML column your picture will be repeated.)

sharepoint_slider_webpart_slider_list

The next step was to create a Document Library called “Script” to store all the Scripts I mentioned above.

sharepoint_slider_webpart_script_library

As you saw in the above screenshot you also need a script called “SPSlider.js”. This script will actually create your Slider Webpart. Here is the code:


<script type="text/javascript" src="/sites/test2/Script/jquery.min.js"></script>
<script type="text/javascript" src="/sites/test2/Script/jquery.SPServices.min.js"></script>
<script type="text/javascript" src="/sites/test2/Script/unslider.min.js"></script>

<style type="text/css">
.hillbillyBanner { position: relative; overflow: auto; }
.hillbillyBanner li { list-style: none; }
.hillbillyBanner ul li { float: left; }
.hillbillyBanner ul {margin-left: -40px;}
</style>

<script type="text/javascript">
jQuery(document).ready(function($) {
var sliderList = "Slider"; // Name of the list that contains slides
var slideContentField = "HTML"; //Name of the Rich text field that has slide content
var slideBackgroundImageField = "Picture"; //Name of the picture field to use as background image
HillbillySlider(sliderList,slideContentField,slideBackgroundImageField);
});
function HillbillySlider(sliderList,slideContentField,slideBackgroundImageField) {
//query to retrieve all items
var query = "<Query><Where><Neq><FieldRef Name='ID' /><Value Type='Number'></Value></Neq></Where></Query>";
//return fields for slide content and background picture
var camlViewFields = "<ViewFields><FieldRef Name='"+slideContentField+"' /><FieldRef Name='"+slideBackgroundImageField+"' /></ViewFields>";
$().SPServices({
operation: "GetListItems",
async: true,
listName: sliderList,
CAMLViewFields: camlViewFields,
CAMLQuery: query,
completefunc: function(xData, Status) {
$(xData.responseXML).SPFilterNode("z:row").each(function() {
var slideContent = ($(this).attr("ows_"+slideContentField));
var picture = $(this).attr("ows_"+slideBackgroundImageField)==undefined?"":$(this).attr("ows_"+slideBackgroundImageField).split(",")[0];
//create slide (li) and append it to other slides
$("#hillbillySlider").append("<li style=\"background-image: url('"+picture +"');\">"+slideContent+"</li>");
}); // end completefunc
//start the slider
$('.hillbillyBanner').unslider();
}
}); // end SPServices call
}
</script>
<div class="hillbillyBanner"><ul id='hillbillySlider'></ul></div>

Please pay attention to the variables listed below. You need to adjust them for your environment.

var sliderList = "<Your-Slider-List-Name>"; // Name of the list that contains slides
var slideContentField = "<Your-HTML-Column-Name>"; //Name of the Rich text field that has slide content
var slideBackgroundImageField = "<Your-Picture-Library-Name>"; //Name of the picture field to use as background image

sharepoint_slider_webpart_content_editor_url

The last step is to create a Content Editor Webpart and add the Url of the “SPSlider.js” script to it.

sharepoint_slider_webpart

That´s it. Your Slider Webpart is ready.

Important note: I did not create this script. I just discovered it. Have a look at the Sources for more information.

You can download the script I used for my example from here.

Sources:

http://summit7systems.com/a-simple-jquery-content-slider-for-sharepoint-200720102013-and-o365/

http://unslider.com/unslider.min.js

Tagged ,

SharePoint – Query List items from External Lists (with jQuery and SPServices)

Hello everyone. Today I tried to find out if it is possible to query External Lists by using jQuery and SPServices so that I can use the gathered data as I wish. And I found out that it is possible. And I´m going to show you how I did it.

The screenshot below shows you that I used the data gathered from an External List to display it in a Content Editor Webpart:

sharepoint_external_list_content_editor_finished

In my example I used an External List called “Location” which I created by importing a SQL Database Table by using the Business Connectivity Services (BCS) and SharePoint Designer with the following columns:

  • Name
  • Address
  • ZIP
  • Country
  • Country_Code

(I will explain how to configure External Lists in a future post if I have the time.)

sharepoint_external_list_example_location

To store my script and the jQuery and SPServices scripts I created a Document Library called “Script”.

sharepoint_external_list_script_library

Here is the GetListItems.js script which will get the list items from the External List:

<script type="text/javascript" src="/sites/test/Script/jquery.min.js"></script>
<script type="text/javascript" src="/sites/test/Script/jquery.SPServices.min.js"></script>

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

$(document).ready(function() {
$().SPServices({
operation: "GetListItems",
async: false,
listName: "Location",
CAMLQuery: "<Query><Where><Eq><FieldRef Name='Country_Code' /><Value Type='Text'>AT</Value></Eq></Where></Query>",
CAMLViewFields: "<ViewFields> <FieldRef Name='Name' /> <FieldRef Name='Address' /> </ViewFields>",
completefunc: function (xData, Status) {
$(xData.responseXML).SPFilterNode("z:row").each(function() {

var liHtml = "<li>" + $(this).attr("ows_Name") + " " + $(this).attr("ows_Address") + "</li>";
$("#tasksUL").append(liHtml);

});
}
});
});

</script>
<ul id="tasksUL"/>

The script will do the following:

It will get all items from the external list, filter them by the column Country_Code and will insert them into a Bulleted List if the Country_Code is “AT”. The returned fields are “Name” and “Address”.

Important note: I only managed to insert the column data into the Bulleted List after I inserted the string “ows_” before the column name (For example: Instead of “Address” I needed to write “ows_Address”). Otherwise it did not work for me. I don´t know why, so if someone knows please let me know.

As always you can download my script from here.

In the next screenshot I added the link of my GetListItems.js script to a Content Editor Webpart.

sharepoint_external_list_content_editor_url

That´s all that needs to be done to make this script work. If you configured everything correct your result will look like the first screenshot in this post. Please keep in mind that it takes some time for External List items to load, so it might take some time before your page has finished loading.

I hope my post was helpful for you.

Sources:

http://www.itidea.nl/index.php/jquery-spservices-and-autocomplete/

http://documentation.agilepoint.com/SupportPortal/DOCS/ProductDocumentation/CurrentRelease/DocumentationLibrary/maps/agileshapeCamlQueryExample.html

https://williamwmy.wordpress.com/tag/getlistitems/

http://social.technet.microsoft.com/forums/sharepoint/en-US/f5371b48-d1aa-4907-ae08-dd7721bd42a2/external-content-type-login-failed-for-user-domainmyuser

Tagged ,

SharePoint – Auto-Fill fields using jQuery and SPServices

Hello everyone. Today I want to show you how you can use jQuery and SPServices (Javascript) to automatically fill fields of SharePoint Forms based on the current user. This can be used to reduce the time users need to fill out forms and to prevent re-entering data you already have.

Unfortunately you need to fulfill all of the following prerequisites before you can begin:

  • SharePoint Server (When you use SharePoint Server 2010 you need an Enterprise License)
  • User Profile Service Application up and running with some Profiles in it (For example: Imported from Active Directory)
  • Download jQuery
  • Download SPServices

After I downloaded all necessary scripts I created a new Document Library called “Script” and added a column (Single line of text) called “Script_Version” to store the version of the scripts (This way I can keep track of the current version and do not need to update my scripts each time a new version is published).

sharepoint_auto_fill_scripts_library

After that I created a new Custom List called “Test” (Not very creative I know). And I added the following columns:

  • LastName (Single line of text)
  • FirstName (Single line of text)
  • Department (Single line of text)
  • EmployeeNumber (Single line of text)
  • Manager (Person or Group)

sharepoint_auto_fill_test_library

Now you need to update the New Form of your Custom List. To edit the New Form enter the following URL into your Browser:

http://<SharePoint-Site>/Lists/listname/NewForm.aspx?PageView=Shared&ToolPaneView=2

Now add a Content Editor Webpart to the page.

sharepoint_add_script_to_new_form

Now add a link pointing to the AutoFillFields.js to the Content Link textbox of your Content Editor Webpart and hide it so your users will not see it when the open up a New Form. When you are finished click on OK and save your work by clicking on Stop Editing.

sharepoint_add_script_to_new_form_content_editor

Here is the code of the AutoFillFields.js Javascript file you need to make this example work:


<script language="javascript" src="/sites/test/Script/jquery.min.js" type="text/javascript"></script>

<script language="javascript" src="/sites/test/Script/jquery.SPServices.min.js" type="text/javascript"></script>

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

$(document).ready(function() {

//Get and Set Department
var userDepartment = $().SPServices.SPGetCurrentUser({

fieldName: "Department"

});

$("input[Title='Department']").val(userDepartment);

//Get and Set LastName
var userLastName = $().SPServices.SPGetCurrentUser({

fieldName: "LastName"

});

$("input[Title='LastName']").val(userLastName);

//Get and Set FirstName
var userFirstName = $().SPServices.SPGetCurrentUser({

fieldName: "FirstName"

});

$("input[Title='FirstName']").val(userFirstName);

//Get and Set Manager (People or Group field)
var columnName = 'Manager';

var managerName;
$().SPServices({
operation: "GetUserProfileByName",
async: false,
AccountName: $().SPServices.SPGetCurrentUser(),
completefunc: function (xData, Status) {
$(xData.responseXML).find("PropertyData > Name:contains('Manager')").each(function() {
managerName = $(this).parent().find("Values").text();
});
}
});

var searchText = RegExp("FieldName=\"" + columnName + "\"", "gi");

$("td.ms-formbody").each(function() {

if(searchText.test($(this).html())) {
$(this).find("div[Title='People Picker']").html(managerName);
return false;
}
});

//Get and Set EmployeeNumber (Custom user property)
var employeeNumber;
$().SPServices({
operation: "GetUserProfileByName",
async: false,
AccountName: $().SPServices.SPGetCurrentUser(),
completefunc: function (xData, Status) {
$(xData.responseXML).find("PropertyData > Name:contains('EmployeeNumber')").each(function() {
employeeNumber = $(this).parent().find("Values").text();
});
}
});

$("input[Title='EmployeeNumber']").val(employeeNumber);

});

</script>

As always you can download my script from here.

The screenshot below shows you that I have added my List as a Webpart to my default page (To show you that this script does also work when the List itself is used as a Webpart).

sharepoint_auto_fill_fields_page

The next step for me was to sign in as a user who has a profile in my User Profile Store (For example: I created a user profile for Lisa Simpson). After I clicked on Add new item (and waiting for about 1-2 seconds) a New Form opened up with all fields I defined in my script already filled out.

sharepoint_new_form_auto_filled_fields

That´s it. You now have the power to fill out fields beforehand to make your users happy 🙂

Sources:

http://www.dhirendrayadav.com/2010/08/modify-newformaspx-and-editformaspx-add.html

http://sympmarc.com/2010/03/16/set-a-people-pickers-value-on-a-form-revisited-with-jquery/

http://sympmarc.com/2010/10/29/capturing-the-current-users-manager-in-moss-using-spservices-and-getuserprofilebyname/

http://basquang.wordpress.com/2010/09/21/spservices-using-jquery-to-auto-fill-current-user-information-in-sharepoint-2010/

 

Tagged ,