KnockoutJS – Creating a Comma-Delimited List of Values

KnockoutJS LogoI’ve been building a lot of great stuff with KnockoutJS lately. It seems that it can enable many – if not all – of the development requirements I have these days, whether I’m building a single-page application (SPA) or just adding a snippet of content to an existing page. I can even build KnockoutJS-enabled “Web Parts” by dropping  a Content Editor Web Part [CEWP] into a page. It doesn’t matter what version of SharePoint it is.

The KnockoutJS documentation is generally very good, but sometimes I find the examples lacking a bit. It’s always tempting to make examples show off too much, which often leads to showing off too little. (I have this same problem with my SPServices documentation and examples.)

A common use case is wanting to display a set of values in a comma-delimited list. Let’s take this example. Say I have an observable array of Ticker objects, like so:

self.Tickers = ko.observableArray([
  {lookupId: 1, lookupValue:"SPLS"},
  {lookupId: 2, lookupValue:"APPL"},
  {lookupId: 3, lookupValue:"GOOG"}
]);

Because I’m pulling data from SharePoint, I want to hang onto the lookupId value along with the text value, which is what I want to display. Because of this a simple Tickers.join(“, “) doesn’t cut it.

I’d like to display the list of tickers like this:

SPLS, APPL, GOOG

Pretty simple, right? But after a little Binglage, I couldn’t find a concise example, thus this post.

If you check the KnockoutJS documentation for foreach, you’ll see that there is a variable available called $index. The $index variable gives you the zero-based index of the current array item.

So if I use foreach on Tickers:

<div data-bind="template: { name: 'Ticker', foreach: Tickers }"></div>

I can use the $index to determine if I should emit a comma. We don’t want to see a comma after the last value, so it requires this small bit of finesse.

<script type="text/html" id="Ticker"><span data-bind="visible: $index() > 0">, </span><span data-bind="text: lookupValue"></span></script>

It’s a little bit bass-ackward, but if the $index value is greater than zero – which it is for all values except the first one, where the index is zero – then we *prepend* a comma to the value.

Yes, I’m using a separate template to emit the tickers. That’s mainly because in my case I’m doing a little bit more than what I’m showing here. However, by creating a separate template, I have a reusable piece of markup. that I can use in many places.

I hope someone out there finds this useful!

References

WordPress and Blackbird Pie: “There was a problem connecting to Twitter”

I have been using WordPress longer than a lot of people. I think I first moved from Windows Live’s blogging platform to WordPress around 2007. Because I’ve been here a long time, I’ve got some plugins that have been around for a long time. One of those is the Twitter Blackbird Pie WordPress Plugin.

The Blackbird Pie plugin was great when it came out. It let you use an embed code to add a live tweet directly into a post. It looked something like this:

[blackbirdpie id=”507693704581500928″]

The id was the unique id for one individual tweet. Twitter was just getting popular and this seemed really cool.

Later, Blackbird Pie got smarter and you could just give it the URL for the tweet on Twitter’s site.

[blackbirdpie url=”http://twitter.com/sympmarc/status/507693704581500928″]

The WordPress crew noticed the Blackbird Pie plugin and they even added it to WordPress in 2010. Instead of using the [blackbirdpie] embed code, you could just drop the url directly into your post. But dang it, it still wasn’t working for me.

I assumed the problem was that Twitter kept changing their interface and APIs and Blackbird Pie stopped working, regardless how you used it. For probably a couple of years now, all my Blackbird Pie -enabled tweet links have been broken. Each one has been showing the message “There was a problem connecting to Twitter”.

I’ve tried quite a few times to fix this, but I’ve gotten nowhere. All of the forum posts out there say things like “It was such a great plugin. Why doesn’t it work anymore?” The owner of the plugin seemed to give up on it, too.

WordPress 4.0 “Benny” came out today and I immediately upgraded, as I am want to do. One of the things I noticed in the release notes was that Twitter embeds are supposed to just work natively. “Well, why haven’t they been working on my site?”, I asked myself.

I don’t know why it occurred to me to do it, but I decided to uninstall the Blackbird Pie plugin. Presto, change-o, all was right with the world. Well, with tweets embedded in my test post. The problem was the Blackbird Pie plugin itself!

You can fix this on your blog by searching for all of the Blackbird Pie embed codes and switching to plain old WordPress embeds.

  • Go to Plugins and Deactivate and/or Deletel the Blackbird Pie plugin
  • Search for all of your posts with the [blackbirdpie] embed code by going to http://YourWordPressBlog/wp-admin/edit.php?s=blackbird
  • For each of those posts, edit it and copy the url to the tweet
  • Delete the embed code line
  • Paste the tweet url into your post

That should do it!

Adding Geolocation Columns to SharePoint Lists

One of the cool things that came along in SharePoint 2013 was Geolocation fields in lists. Using Geolocation fields, we can display Map Views in SharePoint lists. This capability is an awesome way to add visualization to your UI and can really add value in many business processes.

Map View

Image Source: http://msdn.microsoft.com/en-us/library/office/jj656773(v=office.15).aspx

Think about it. You could show:

  • A map of your customers in a region
  • A map of your office’s location on its Intranet page
  • Deliveries you’ve made in the last 30 days
  • etc.

Unfortunately, at the present time in SharePoint 2013 on premises and SharePoint Online (Office365), “The Geolocation column is not available by default in SharePoint lists. To add the column to a SharePoint list, you have to write code.” (See How to: Add a Geolocation column to a list programmatically in SharePoint 2013)

For whatever reason, there’s no way to add a new Geolocation field via the UI. Instead you have to go through some hoops with PowerShell or script. See the following articles for great tutelage on how to do this:

As I understand it, there’s an MSI package (SQLSysClrTypes.msi)that must be installed manually on the Web Front Ends (WFEs) in an on premises installation to enable Geolocation fields, but this is already in place in SharePoint Online. Given this, we should be able to add Geolocation columns to lists via the UI without PowerShell or admin intervention.

This doesn’t sit well with me. At some of my clients, getting an admin to add something to the WFEs or run PowerShell requires an act of Congress. These Geolocation capabilities are too powerful a SharePoint feature to keep them under wraps.

To wit, I’ve created a suggestion called Adding Geolocation Fields to SharePoint Lists on the Office Development UserVoice site. If you’d like to be able to use Geolocation fields in your SharePoint solutions – at least on Office365 – head on over and cast your vote(s). Remember, Microsoft is listening!

Harvey Balls Redux – Display Templates for Site Columns by Dave Paylor

It may surprise you to know that one of my most popular blog posts has nothing to do with SharePoint, knowledge management, performance improvement, jQuery, client side coding, SPServices, or anything else you might expect. It’s one I wrote years ago (June 17, 2009, to be exact) called Harvey Balls for Office Documents. I though it was a throwaway post at the time, but it’s number 11 on the hit parade.

Title Views
Adding Script into a Content Editor Web Part (CEWP) in SharePoint 2010 32,547
Microsoft Excel Error: “There was a problem sending the command to the program.” 25,816
Adding jQuery+SPServices to a SharePoint Page: Step One, Always 23,973
Displaying Links Lists’ URLs in a Content Query Web Part (CQWP) in SharePoint 2010 22,971
Populating a SharePoint List Form with the Current User Information 20,789
Showing All Versions of “Append Changes to Existing Text” in a Data View Web Part (DVWP) 19,502
Using a DataSource in a Data View Web Part (DVWP) in a Different Site in SharePoint Designer 2010 18,904
The SharePoint 2010 “List View Lookup Threshold” and Why We Don’t Change It 18,848
Active Directory Groups vs. SharePoint Groups for User Management: A Dilemma 17,169
Working with SharePoint People Pickers with jQuery: A New Function Called findPeoplePicker 15,742
Harvey Balls for Office Documents 15,574

Harvey Balls are something that you probably have run across in one place or another. They can be used to give information about where something ranks or how far something has progressed at a glance. Consumer Reports magazine (and subsequently their Web site ConsumerReports.org) here in the US has used them for decades to rank products.

Here’s an undated example I found out on the Web:

Consumer Reports Harvey Balls

Dave Paylor (@DaveAtOBS) and I were talking at the Auckland airport after the New Zealand SharePoint Conference (an awesome conference – don’t miss it next year!) and somehow the topic of Harvey Balls came up.

Dave took our conversation as a challenge. He went home and came up with a Display Template for a SharePoint Site Column that will display that Site Column as Harvey Balls. Take a look at Dave’s post Display Templates for Site Columns – Harvey Balls.

This is an excellent example of the power of Display Templates. In the past, we would have had to deploy server-side code to create a new Field Type. I’ve seen very few people actually do that, probably because it was a relatively invasive project. Display Templates are something that can be added to a Site Collection by someone who knows JavaScript using SharePoint Designer. It’s not a non-developer task, but it’s doable by a lot of citizen developers out there.

Unfortunately, attaching the Display Template to a Site Column requires PowerShell. Dave’s added an item to the Office Development User Voice site called JSLink on Site Columns. I’ve voted for it, and if you’d like to create similar types of goodness in your SharePoint sites, you should vote for it, too. Microsoft is really watching the suggestions on that User Voice site and acting on them. If you have any other suggestions, please make them there!

Detecting the Current User’s Regional Settings with jQuery

I noticed a nice little trick going by in my Twitter feeds today.
2014-08-20_19-09-43I’ve always wanted to know how to do this. Displaying the right formats for dates and times as well as the right offset from UTC is a real challenge from the client side. There’s a fantastic library called Moment.js that I use on just about every project these days, but it only does the full job if you know the user’s locale and timezone.

The post on StackExchange gave a little snippet of script which came from an old MSDN Forums post from 2009. Kudos to Peter Holpar for the original idea.

The script basically screen-scrapes the values from the Language and Region settings page. I don’t mean that disparagingly at all; screen-scraping is how the SPGetCurrentUser function in my SPServices works. If it gets the job done and is reliable, the old art of screen-scraping – or should we call it plumbing the DOM with AJAX? – is just great.

Note that you’ll need to have jQuery loaded to use its AJAX function.

Here’s the script as-is from the StackExchange post. It was originally intended for SharePoint 2010.

var url = ctx.HttpRoot+"/_layouts/regionalsetng.aspx?Type=User";
$.get(url,function(data){
    $(data).find("select[name='ctl00$PlaceHolderMain$ctl00$ctl00$DdlwebLCID']").find(":selected").each(function(){
        var lcid  = $(this).attr("value");
        var cultureInfo  = $(this).text();
    });
});

I just tested it out in SharePoint Online on Office365 and this is the version that works for me. Note that I simplified the jQuery selectors to look just for the important ending text in the name attribute. I’ve also re-scoped the variables so that they are available outside the $.get call. If you want to use this snippet, you’ll probably need to adapt it for your environment. The alert at the end is jut there to show you that it works.

var url = _spPageContextInfo.webAbsoluteUrl+"/_layouts/regionalsetng.aspx?Type=User";
var lcid, cultureInfo, timeZone;

$.get(url,function(data){
  $(data).find("select[name$='LCID'] option:selected").each(function(){
      lcid  = $(this).attr("value");
      cultureInfo  = $(this).text();
  });
  $(data).find("select[name$='TimeZone'] option:selected").each(function(){
    timeZone  = $(this).text();
  });

  alert(lcid + "::" + cultureInfo + "::" + timeZone);
});