How to add a floating menu to a page in SharePoint 2010

Problem:

My customer wanted to had a floating menu to the NewForm.aspx page for one of the lists. The floating menu will stay on the top left corner of the page as page scrolls.

Demo:

This was done on our internal website, but it works similar to this post http://css-tricks.com/examples/ScrollingSidebar/

Solution:

After a few searches online, I found it’s often done in HTML using CSS or JavaScript. See the References section for the list of articles I found relating to this feature.

The article worked really well for me is this one. The article talked about how to make the quick launch float, but I changed the div name and works for a  normal menu.

Here is how:

1. Go to the article page, download the stickyQL.js file.

2. Open the stickyQL.js file, change

var elem = "#s4-leftpanel";

to

var elem = "#YourFloatingDivID";

3. Save the file in the site collection’s style library. We’ll need to reference the file later.

4. Go to the site and open SharePoint Designer. From the left pane, select Master Pages.

5. Open the v4.master. Find </head>. Add the following lines before </head>

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="[servername]/Style Library/MyJS/stickyQL.js"></script>

6.Go to the NewForm.aspx page, edit the page and add a new content editor web part.

7. Add the following code to the CEWP’s HTML source.

<div id="sidebar" style="width: 15%; float: left; z-index: 1;">Some text on the floating menu.</div>

8. Click “Stop Editing” to exit editing.

References:

Floating menu in HTML using CSS or JavaScript

Floating sidebar in HTML using CSS and JavaScript

Sticky or Floating box in SharePoint 2013 site’s Sidebar

Advertisements

Using SPServices to provide data to autocomplete field on Nintex

Environment:

SharePoint Server 2010, Nintex Form 2010, SPServices 2013.01

Problem:

In one of our Nintex form, we need to allow people to search for items that are stored on another list and set the search result to be the input field’s value.

Narrative:

Initially, I found a method called $().SPServices.SPAutocomplete from the SPServices site . In their SP2007 demo site, it worked perfectly on a normal form. So I copied the code to my Nintex form and it threw a error saying “Column is not an input control or is not found on page”. I searched that error message and found this article which had the same error. After reading it, I realise that Nintex form might have changed the control id therefore, the script couldn’t find it. The code posted by hilary86 worked the trick.

Result:

This is the screenshot of my final result. When user start typing in the JournalTitle input field, items that contains the typed in words will show in the dropdown.

To delete

How to make it happen:

  1. The items showed in the autocomplete dropdown list are stored in another SharePoint list. So first of all, we need to create a SharePoint list and add a few items to the list. I called it “Journals”.
  2. Download the SPServices file from http://spservices.codeplex.com/, unzip it.
  3. Open the jquery.SPServices-VersionNumber.min.js  file and search for “(jQuery)”. It should be in the last line of the file. Replace it with “(NWF$)”. Save the file.
  4. Upload it to the site collection’s Style Library.
  5. Create another js file in the Style Library, my one called NF_AutoComplete.js
  6. Type the following code to the NF_AutoComplete.js
    NWF$(document).ready(function() {   
       //The source data for the autocomplete is the Journals list  
       //Store the journal titles in a array variable  
       var externalParties = [];     
       NWF$().SPServices({      
          operation: "GetListItems",      
          async: false,      
          listName: "Journals",      
          CAMLViewFields: "<ViewFields><FieldRef Name='Title' /></ViewFields>",   //the name needs to be changed accordingly   
          completefunc: function (xData, Status) {        
             NWF$(xData.responseXML).SPFilterNode("z:row").each(function() {          
                externalParties.push(NWF$(this).attr("ows_Title"));        
             });      
          }    
       });        
       //journalinput is added on the control in the NF  
       NWF$("#" + journalinput).autocomplete({      
          source: externalParties  
       });
    });
  7. Go to the Nintex Form. In the ribbon, navigate to the form’s Settings. Expand the Advanced section, add the URLs of the  jquery.SPServices-VersionNumber.min.js  and NF_AutoComplete.js to the Custom JavaScript Includes box. Save it.
  8. Click on the input box control which will display the autocomplete and click Control Settings from the ribbon.
  9. Expande the Advanced section, change the Store Client ID in JavaScript variable value to Yes. Enter the id used in the code in Step 6. So for me, it was journalinput. Save it.
  10. Make sure you publish the form.
  11. That’s it. There are some other options can be added to the autocomplete, change to suit your needs.

References:

A big thanks to Marc Anderson and the team who developed SPServices!!

Three ways of opening a list form in a Modal Dialog Box

This post described three ways of opening a list form in a Modal Dialog Box using JavaScript in a Content Editor Web Part.

First one simply add

onclick="javascript:SP.UI.ModalDialog.showModalDialog({ url: '../Lists/GBE/NewForm.aspx', title: 'User Survey' }); return false;"

to any hyperlinks

Second one calls a js function which has call backs

Third one is similar to the second one but with a check duplicates process. It uses client object model to check if an entry has been entered before new form is submitted.

The post also included an URL of how to add javascript to a custom web part

Create contact form using ECMAScript/JavaScript Client Object Model

My client has asked to create a request form based on a list which records all the requests in SharePoint 2010.

Problems/Requirements:

  • Only one column in the request list which is the default column created when the list is created. It has a column type of “Single line of Text”. This column can’t be deleted or changed to a different column type.
  • Display that column as a muli-line text box rather than a single-line input box and have the message wrapped.
  • Once the request is sent successfully from the form, display a message to the user “Request Sent!”

Final delivery:

Request

Features:

  • The user can only enter 255 characters in the box as specified in the Request column in the list. Anything over 255 will be truncated straight away. The reason it’s set to 255 is because in the list, the column has “Maximum number of characters” set to 255.
  • Once a request is submitted successfully, a message will pop up to indicate the user.
  • If something accidently clicked the “Send” button without typing a message, an error message will pop up and the empty request won’t be added to the list.
  • All done through a content editor web part using ECMAScript, javascript and html.
  • This web part can be reused by changing the field names in the script to match with the list. However, I haven’t tried with lists containing fields other than single/multiple line of text.

Code:

<script type="text/ecmascript">  
function SendEnquiry() {  
  var el = document.getElementById("Message");
  if (el.value == '')  {   
    alert('Please enter a message.');   
    return false; 
  }  
  else  {   
    var MessageField = document.getElementById("Message");     
    SaveInContactUs(MessageField.value);  
  } 
}   
function SaveInContactUs(Message) {  
  var context = new SP.ClientContext.get_current();   
  var web = context.get_web();   
  var list = web.get_lists().getByTitle('ImageRequest');   
  var listItemCreationInfo = new SP.ListItemCreationInformation();   
  var newItem = list.addItem(listItemCreationInfo);     
  newItem.set_item('Title', Message);    
  newItem.update();    
  context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed)); 
}   
function success() {  alert('Your message is submitted!'); }   

function failed(sender, args) {  alert('failed. Message:' + args.get_message()); }
function textLimit(field, maxlen) { if (field.value.length > maxlen)  field.value = field.value.substring(0, maxlen);  } 

</script>
<div style="width:300px">  
  <p><strong>Image Request Form</strong></p>  
  <p>I would like to have an image available in the gallery depicting.</p>  
  <div>   
    <textarea id="Message" name="Message" onkeyup="textLimit(this, 255);" style="font-size:11pt; width:300px; height:150px" ></textarea>     
    <br/>   
    <div style="text-align:center;">    
      <input type="submit" onclick="Javascript:SendEnquiry();" value="Send" style="width: 100px; height: 30px; font-weight: bold;">   
    </div>  
  </div> 
</div>

Reference:

This article really got me started. Thanks so much!

http://www.learningsharepoint.com/2011/10/03/create-contact-form-using-ecmascriptjavascript-client-object-model-sharepoint-2010/

Say if I have a contact form instead and I would like to get the user to receive a copy of their submitted message in their email, I can probably include the code in this article. (In theory)

http://stackoverflow.com/questions/7097363/send-email-with-javascript

If the form included a dropdown list, the code in this article may be useful.

http://haseebakhtar.wordpress.com/2012/07/10/how-to-retrieve-all-choice-field-values-using-ecmascript-sharepoint-2010/

Form based validation in js

http://stackoverflow.com/questions/6810985/validate-form-required-fields-based-on-class

Further improvement:

The validation on the form is pretty lame. If someone just entered spaces in the text box, it would still submit the form successfully. So how can I have a better validation for a required field? And what if I have a email or number field, what validation would I need? You are welcome to post solutions/thoughts in the comment area.

Create a custom HTTP404 rediect page in SharePoint 2010

By default, SharePoint takes you to its own 404 NOT FOUND page if you enter an Url which does not exist in the site.

My client has requested to display a 404 Not Found page with the custome master page and page layout style. After a few searches, some articles are found. Chaks’ and Ritu’s ones were particular helpful.

Default SharePoint 404 error pages are stored at this location:

14\TEMPLATE\LAYOUTS\1033\ERRORV4.html
14\TEMPLATE\LAYOUTS\1033\sps404.html

1. Create a error page on the site that has the publishing page layout and custom master page. I created a page called customError.aspx under the root site collection under the Pages folder.

2. Make a copy of sps404.html and name it custom404.html. Place it in the same location as sps404.html

3. Open custom404.html. Change the URL inside STSNavigate to your customError.aspx page url

customError

4. The next step is to set custom404.html as the 404 redirection page for your specific web application. we are accomplishing this by creating a custom404 feature and as the feature activates, it sets the FileNotFoundPage to the custom404.html. custom404.html then redirects the page to customError.aspx page

Open Visual Studio, create a new project, choose Empty SharePoint Project and change to .Net Framework 3.5. Name the project “PageNotFound”

Choose Deploy as a farm solution

Right click on Features, Add Feature, change the Scope to Site.

Right click on Feature1.feature, Add Event Receiver.

Open the EventReceiver.cs file, add this line above the namespace.

using Microsoft.SharePoint.Administration;

Paste the following code inside public class.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
      if (properties != null)
      {
        SPSite currentSite = (SPSite)properties.Feature.Parent;
        SPWebApplication webApplication = currentSite.WebApplication;
         webApplication.FileNotFoundPage = "custom404.html";
         webApplication.Update();
      }
}

Right click on the project and Deploy.

Now if you go to a incorrect page, you will be redirected to your custom error page.

Reference:
http://blog.mastykarz.nl/sharepoint-2010-page-not-found-404/
http://chakkaradeep.com/index.php/customizing-the-404-redirection-in-sharepoint/
http://ritutechworld.blogspot.co.nz/2010/06/custom-error-page-in-sharepoint-2010.html
http://microsoftechies.wordpress.com/2012/10/08/error-occurred-in-deployment-step-activate-features-unable-to-cast-object-of-type-microsoft-sharepoint-spweb-to-type-microsoft-sharepoint-spsite/

JavaScript – Open links on page in new window/tab in SharePoint 2010

There are two types links on page. One is that links added in the content as html. The other type is that links in a document library and displayed on page via DVWP.

Here is how to open the first type of links in new window:

1. Attach a javascript file in the master page or just add the javacript in the header section

2. Here is the javascript:

//add an entry to the _spBodyOnLoadFunctionNames array 
//so that our function will run on the pageLoad event 
_spBodyOnLoadFunctionNames.push("rewriteLinks");
function rewriteLinks() {  
//create an array to store all the anchor elements in the page   
var anchors = document.getElementsByTagName("a");   
//loop through the array   
for (var x=0; x<anchors.length; x++) {    
//set the target attribute to be blank to open in new window    
anchors[x].setAttribute('target', '_blank');   
} 
}

3. In IE, open Internet Options. General tab -> Tabs -> Settings ->When a pop-up is encountered -> Always open pop-ups in a new tab

Here is for the second type:

1. Attach a javascript file in the master page or just add the javacript in the header section

2. Here is the javascript:

$(document).ready(
  function ()
  {
    // has to be on an interval for grouped doc libraries
    // where the actual links are loaded only once a group
    // is expanded
    setInterval(
      function ()
      {
        $("a[onclick*='return DispEx'][target!='_blank']")
          .attr("target", "_blank")
          .removeAttr("onclick");

        // document type icons
        $("td.ms-vb-icon>img[onclick]:not([documentUrl])")
          .click(function (e)
          {
            window.open($(this).attr("documentUrl"), "_blank");
            e.stopPropagation();
            e.preventDefault();
            return false;
          })
          .each(function ()
          {
            $(this).attr(
            "documentUrl",
            $.trim(String($(this).attr("onclick"))
              .split("=")[1]
              .replace(/["'{}]/g, "")
              .split(";")[0])
            );
            this.onclick = null;
          });
      },
      500
    );
  }
);

Reference:
http://www.benramey.com/2011/04/25/opening-all-sharepoint-2010-documents-in-a-new-window/
http://www.sharepointkings.com/2008/07/open-documents-in-new-window.html

Add a printer friendly button to SharePoint publishing page

One of the request from my client is to allow user to print a page with only text content on it. This feature is quite common in many websites.

After reading Kathy Hughes “Microsoft SharePoint Designer 2010 Unleashed”, it’s pretty easy to do so in SharePoint 2010.

Scenario: I have 3 custom page layout for my site, home page layout, landing page layout and detail page layout. I only want to have a print button on pages that uses content page layout.

Here are the steps:

1. Create a new CSS file in the site collection’s Style Library and name it print.css. In this file, you can try hide all the components that you don’t want to see in the print view.

2. Open detail page layout. Add the following html inside the PlaceHolderMain tag.

< a id=”printer” onclick=”myPrinter(‘printer’)” href=”#” target=”_blank”><img src=”/Style Library/images/printer.png”></a>

3. On the same page, scroll to the top. Find the closing tag of PlaceHolderAdditionalPageHead. If you don’t have this tag, you need to add it first. Add the following JavaScript immediate before the closing tag. Of course you can add these code to a js file and add the link here instead.

<script type=”text/javascript”>
//if the url doesn’t contain printfriendly, use the normal style sheet
if (location.search.indexOf(‘printfriendly’) == -1){
document.write(‘<link rel=”stylesheet” type=”text/css” href=”/Style Library/css/gw_content_style.css”/>’);
}
//otherwise use the print style sheet and open the print window
else
{
document.write(‘<link rel=”stylesheet” type=”text/css” href=”/Style Library/css/gw_print.css”/>’);
window.print();
}

function myPrinter(id)
{
//if url doesn’t contain a question mark
if(location.search.indexOf(‘?’) ==-1)
{
var qrystr = document.getElementById(id).href;
//if  the url doesn’t contain a hash
if (qrystr.indexOf(‘#’) == -1)
{
//use the existing url.
//This means the button has been pressed before
//so the printfriendly parameter is already added.
document.getElementById(id).href = qrystr;
}
//otherwise the button hasn’t been pressed before
//so remove the # and add the printfriendly parameter
else
{
var newstr = qrystr.replace(‘#’, ‘?printfriendly=true’);
document.getElementById(id).href = newstr;
}
}
//this is used for pages like DisplayFullStory?ID=3 which has a parameter
else
{
var qrystr = document.getElementById(id).href;
if (qrystr.indexOf(‘#’) == -1)
{
document.getElementById(id).href = qrystr;
}
else
{
var newstr = qrystr.replace(‘#’, ‘&printfriendly=true’);
document.getElementById(id).href = newstr;
}
}
}
</script>

4. That’s it. When you test it, make sure you go to a page that uses the detail page layout.

 

Reference:

http://www.codingforums.com/archive/index.php/t-80517.html