SharePoint JavaScript Multi Select Choice Field – return nice format

Getting some event items from SharePoint in JavaScript? Have a multiselect choice field for caragories? Here's some handy JavaScript for cleaning out the rubbish ';#' and returning a nice comma delimited list

function cleanArray(actual){
  var newArray = new Array();
  for(var i = 0; i<actual.length; i++){
      if (actual[i]){
        newArray.push(actual[i]);
    }
  }
  return newArray;
}

function getEventCategory(inCategoriesString)
{
        var eventCateory = '';
        var eventCategories = inCategoriesString.split(';#');
        eventCategories = cleanArray(eventCategories);
        
        if (eventCategories.length == 1)
        {
        	eventCateory = eventCategories[0];
        }
        else
        {
        	for (i = 0; i < eventCategories.length; i++)
        	{
        		if (i == eventCategories.length - 1)
        		{
        			eventCateory += eventCategories[i];
        		}
        		else
        		{
        			eventCateory += eventCategories[i] + ', ';
        		}
        	}
        }

        return eventCateory;
}

 

ContentByQuery not working with OrderBy

I had some issues where I put a content by query web part in a page and when I added the OrderBy clause, it just stopped showing anything with no errors. I ended up putting the whole query on one line with no spaces and it started working. Not that it worked with spaces and line breaks as a normal where query, but only stopped working when I added the orderby. Also if your data isn't showing, check the data mapping view fields :).  

 

<Publishing:ContentByQueryWebPart runat="server" 
            	        ChromeType="TitleOnly" 
            	        Title="Executive Team Update"
				        ItemXslLink="{{SITE_COLLECTION_URL}}/Style Library/site/stylesheets/itemstyle.xsl"
				        ItemStyle="ExecutiveUpdate"
                        ItemLimit="1"
                        DataMappingViewFields="{94f89715-e097-4e8b-ba79-ea02aa8b7adb},Lookup;{108fed99-9aa6-4776-9065-23c19a63b787},Image;{fa564e0f-0c70-4ab9-b863-0177e6ddd247},Text;{f55c4d88-1f2e-4ad9-aaa8-819af4ee7ee8},HTML;{f55c4d88-1f2e-4ad9-aaa8-819af4ee7ee8},HTML;{8c06beca-0777-48f7-91c7-6da68bc07b69},DateTime;{446b839b-6220-4c3d-8444-9041faf31257},Choice;"
				        DataMappings="TeamMember:{446b839b-6220-4c3d-8444-9041faf31257},ExecutiveTeamMember,Choice;|PublishingPageContent:{f55c4d88-1f2e-4ad9-aaa8-819af4ee7ee8},PublishingPageContent,HTML;|Description:{f55c4d88-1f2e-4ad9-aaa8-819af4ee7ee8},PublishingPageContent,HTML;|Title:{fa564e0f-0c70-4ab9-b863-0177e6ddd247},Title,Text;|LinkUrl:{94f89715-e097-4e8b-ba79-ea02aa8b7adb},FileRef,Lookup;|Created:{8c06beca-0777-48f7-91c7-6da68bc07b69},Created,DateTime;|ImageUrl:{108fed99-9aa6-4776-9065-23c19a63b787},FeaturedImage,Image;|"
                        QueryOverride="<OrderBy><FieldRef Name='Modified' Ascending='False' /></OrderBy><Where><Eq><FieldRef Name='ContentType' /><Value Type='Computed'>Executive Team Update Page</Value></Eq></Where>" />

 

Check if user is in a group in JavaScript

Useful if you want to show/hide buttons or html/controls on a page layout or in masterpage. Details from http://stackoverflow.com/questions/8841985/sharepoint-10-lists-want-to-limit-form-fields-per-user-groups/8847834#8847834

Link jquery 11 and spservices into your masterpage through script links or custom actions

function:

function IsGroupMember(GroupName)
{
    var isGroupMember = false;
    $().SPServices({
        operation: "GetGroupCollectionFromUser",
        userLoginName: $().SPServices.SPGetCurrentUser(),
        async: false,
        completefunc: function(xData, Status) {
            if($(xData.responseXML).find("Group[Name='" + GroupName + "']").length == 1)                
            {
                isGroupMember = true;
            }
        }
    });
    return isGroupMember;
}

Call function

Admin_Group = "Owners";
if (IsGroupMember(Admin_Group))
    $('.div').show;
else
    $('.div').hide();

 

Create a link in JavaScript to create a new page in pages library with custom content type

The following code should go in a page layout. This is useful for landing pages where users want to be able to quickly create pages.

Replace the content type id and url information. To find out the content type id you can navigate to the create page for your content page and look at the url. Note that this only works if you are deploying your content types with the same id every time. 

var siteCollectionUrl = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl;
                var returnURL = siteCollectionUrl + "/newsandevents/Pages";
                var url = '/newsandevents/_layouts/15/CreatePage.aspx?List=Pages&ContentTypeId=0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900DBB9F5D2AD4B436592E51AF81B2B2560007821B1F1235E524B982C1512AFCF515C' + returnURL;
                $('.jsCreateUpdate').html('<a href="' + siteCollectionUrl + url + '">+ Create Update</a>');

 

html:

<div class="create-update jsCreateUpdate">

</div>

 

Get radio button selected text from SharePoint choice field on page layout – JQuery, bind to change event

So I couldn't find anything obvious for this so chucked this together, hopefully useful for someone else 🙂

Page layout:

<div class="featured-breaking">
        <SharePoint:RadioButtonChoiceField FieldName="FeaturedBreaking" runat="server"></SharePoint:RadioButtonChoiceField>
</div>

JavaScript:

var selectedVal = "";
var selected = $(".featured-breaking input[type='radio']:checked");
if (selected.length > 0) {
    selectedVal = selected.parent().attr('title');
}
console.log(selectedVal);

On load, bind to change event:

<script type="text/javascript">
	_spBodyOnLoadFunctionNames.push("LoadNewsEntryPage");
	function LoadNewsEntryPage() {
		$(".jsFeaturedBreaking input[type='radio']").bind("change", FeaturedBreakingChanged);
		FeaturedBreakingChanged();
	}

	function FeaturedBreakingChanged() {
		var selectedVal = "";
		var selected = $(".jsFeaturedBreaking input[type='radio']:checked");
		if (selected.length > 0) {
			selectedVal = selected.parent().attr('title');
		}
		if (selectedVal == "N/A") {
			$('.jsExpiresOn').hide();
		}
		else {
			$('.jsExpiresOn').show();
		}
	}
</script>

 

Creating an administrator token in Yammer

Update: October 2017, this is all still relevant! Tested myself this month on a project.

Create an Admin access token

  1. Sign into Yammer as Yammer Admin via https://www.yammer.com
  2. Go to https://www.yammer.com/client_applications and register a new app.

Register a New App – Required Fields:

Description

Application Name:

Token Requestor App

Organization:

Organization name

Support e-mail:

An email address, which users of your app can contact for support.

Website:

Your organization’s website.

Redirect URL:

https://www.yammer.com

 

  1. Copy your Client ID, Redirect URI from the Application Information page.

  1. Paste this url into your browser, where client_id, redirect uri are the values obtained from step 4 above (replace including the brackets):

https://www.yammer.com/oauth2/authorize?client_id=[:client_id]&redirect_uri=[:redirect_uri]

  1. Copy the “code=” value from the URL created.
  2. Paste this url into your browser, where client_id, client secret are obtained in step 4 above. Code is the code from step 6 (replace including the brackets).

https://www.yammer.com/oauth2/access_token.json?client_id=[:client_id]&client_secret=[:client_secret]&code=[:code]

  1. Copy the “token:” value from the resulting JSON. Store it e.g. in Notepad.

You have your admin token! 

Thanks to Roland Oldengarm for putting together these instructions: https://rolandoldengarm.wordpress.com/

 

PowerShell to add and sort Managed Metadata navigation – on premises

Here's a useful snippet of PowerShell code for creating Managed Metadata navigation and sorting it – on premises

Add-PSSnapin Microsoft.SharePoint.Powershell

# Change these variables based on environment ****
$centralAdminURL = "http://centraladmin"
$siteCollectionURL = "http://sitecollection"

$termStoreName = “Managed Metadata Service”
$termGroupName = “Navigation Group”
$termGroupDescription = "Group Description"
$termsetName = "Navigation Termset"
$termSetDescription = "Termset Description"
# *************************************************


function CreateTerm($parent, $name, $url)  
 {  
    Write-Host "Adding term $name to parent $parent.Name"  
    $term = $parent.CreateTerm("$name", 1033)  
    $term.IsAvailableForTagging = $false    
    $newUrl = $url
    if(!$url.ToLower().Contains("http"))
    {  
        # Logic to append site url to relative path to create complete url which is needed for Simple Link Navigation
        $newUrl = $url
    }

    $term.SetLocalCustomProperty("_Sys_Nav_SimpleLinkUrl", $newUrl)   
    return $term  
 } 

$site = Get-SPSite -Identity $centralAdminURL
$session = Get-SPTaxonomySession -Site $centralAdminURL
$termStore = $session.TermStores[$termStoreName]

# Remove if exists already
$group = $termStore.Groups[$termGroupName]
if ($group -ne $null)
{
    Write-Host "Removing terms"
    $group.TermSets|foreach{
        $_.Delete()
    }
    $group.Delete()
    $termstore.CommitAll()
}

# Create term group and term set
$group = $termstore.CreateGroup($termGroupName)
$group.Description = $termGroupDescription
$termStore.CommitAll()

Write-Host "TermGroup - $termGroupName created successfully"  

$termSet = $group.CreateTermSet($termsetName,1033)
$termSet.Description = $termSetDescription
$termSet.IsAvailableForTagging = $false
$termSet.IsOpenForTermCreation = $false
$navigationSet = $group.TermSets[$termsetName]
$navigationSet.SetCustomProperty("_Sys_Nav_IsNavigationTermSet", "True")
$termStore.CommitAll()

Write-Host "TermSet - $termsetName created successfully"  

# Create terms

# Home
$homeTerm = CreateTerm $termSet "Home" $($siteCollection + "/")

# Other term set

$otherTerm = CreateTerm $termSet "Other Term" $($siteCollection + "/subsite/Pages/home.aspx")

$termStore.CommitAll()

# Create sub terms
$otherTermSub1 = CreateTerm $otherTerm "Other Term Sub 1" $($siteCollection + "/subsite/Pages/othertermsub1.aspx")
$otherTermSub2 = CreateTerm $otherTerm "Other Term Sub 2" $($siteCollection + "/subsite/Pages/othertermsub2.aspx")
$otherTermSub3 = CreateTerm $otherTerm "Other Term Sub 3" $($siteCollection + "/subsite/Pages/othertermsub3.aspx")
$otherTermSub4 = CreateTerm $otherTerm "Other Term Sub 4" $($siteCollection + "/subsite/Pages/othertermsub4.aspx")

# Set sort order
$customSortOrder = $otherTermSub1.id.ToString() + ":" + $otherTermSub2.id.ToString() + ":" + $otherTermSub3.id.ToString() + ":" + $otherTermSub4.id.ToString()
$otherTerm.CustomSortOrder = $customSortOrder

$termStore.CommitAll()

Write-Host "Terms for Term Set - $termsetName created successfully"   

 

How to connect to SharePoint Online

Running PowerShell with SharePoint on premises is pretty easy, you jump on the server and run up PowerShell or PowerShell ISE and start connecting and commanding. So how do you connect to SharePoint online from either a server or your local machine?

You need to install Windows Management Framework 3.0 and SharePoint Online Management Shell. The cool thing about SharePoint online and cmdlets is that you can run them from any machine with the tools installed.

Create a new PowerShell script by either opening a new notepad document and saving it as a '.ps1' file, or by opening PowerShell ISE. Paste in the following code and change the user, password and URLs.

Clear-Host
$spOnlineUser = ''
$spOnlinePassword = ''
$spOnlineSiteAdminUrl = 'https://pkswlgsandbox-admin.sharepoint.com'
$spOnlineSiteUrl = 'https://pkswlgsandbox.sharepoint.com/sites/devicechannels'

$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $spOnlineUser, $(convertto-securestring $spOnlinePassword -asplaintext -force)
Connect-SPOService -Url $spOnlineSiteAdminUrl -Credential $cred
Write-Host "Connecting to " $spOnlineSiteUrl

$site = Get-SPOSite -Identity $spOnlineSiteUrl
Write-Host "Success!!" -ForegroundColor "Green"
$site

Now that you have a .ps1 file ready, run SharePoint Online Management Shell as Administrator and run your script.

Quick side note, if you get the following error "….ps1 cannot be loaded because running scripts is disabled on this system….", you need to run the following command "Set-ExecutionPolicy RemoteSigned" and click "Yes".

In SharePoint Online Management Shell:

In PowerShell ISE:

Once you have scripts running, and if you have set your credentials and URL's correctly, you should see the following:

I love PowerShell ISE, so if your planning on writing many scripts you should use it. It allows editing and running of scripts on one screen as well as intellisense and debugging.


So, what can you actually do against SharePoint online?? The cmdlets available out of the box are very limited, which means you need to write CSOM in your PowerShell. Here is a post by Chris O'Brien with more information on CSOM in PowerShell. You can also start to use custom CMDlets:

Māori spell checking in SharePoint 2013 and SharePoint Online

There isn't (as far as I can tell from anywhere) a Māori dictionary in SharePoint, even though you can set it as a prefered language in your profile. I found a post from SharePoint 2010 which specifies a work around for setting another language as the spell check language by adding some JavaScript into your master page, you can also add the code into a page layout. This worked fine for French when I tried it, but didn't work for Māori which uses the local ID 1153. Instead I got the following message "The spelling check cannot be completed because there is no dictionary installed for the current language". Dictionaries must only be installed when a language pack is installed, of which there isn't a huge variety.

It's not ideal, but you can still include Māori words in the dictionary. Keep reading!

In SharePoint 2010, you could add a custom dictionary which would be used by spell check throughout the site. This hasn't changed in SharePoint 2013 and SharePoint Online.

This works per site collection:

  • Create a new word document (if you don't require macrons then you can just use notepad to create the .txt file and follow the same steps)
  • Add a word to each line, as in the screen shot below

    Adding words to custom dictionary

  • Save the file as a .txt file named "Custom Dictionary.txt" – this has to be the exact name of the file, select "Other encoding" and set Inicode (UTF-8)

    saving the custom dictionary

  • In the root of your site collection, create a document library named exactly "Spelling"
  • Upload your Custom Dictionary.txt file into the document library

The words you added to the dictionary will now be correct spelling.

example editing html field with new dictionary