Tuesday, December 27, 2011

Get Unique values in XSLT

While working with dataview webpart, we some times have the requirement to get unique values from the xml data. The following code will help us to fetch unique values from an xml data

If you observe the xslt of the webpart, there will be a variable which is populated with all the rows

<xsl:variable name="Rows" select="/dsQueryResponse/Rows/Row" />

change the above line of code with the below line

<xsl:variable name="Rows" select="/dsQueryResponse/Rows/Row[not (@Title=preceding-
sibling::Row/@Title)]" />

This will fetch the unique "Titles" from the xml data.



"Please wait while scripts are loaded..." message in status bar

While working with sharepoint front end development using Javscripts, some times I continuously receive the message in status bar "Please wait while scripts are loaded...". It continues to display the same even when the page is loaded completely.

This is because my javscript code is failing but it wont throw the actual error message but this status message.
This happens because of the order of the events triggered. as one of the function was checking whether the page has loaded which is being stopped by the exception in my javascript function and the status indefinetly shows this message.

To trace the actual error message place the following line of code before your code.

g_pageLoadComplete = true
By this code, you can actually see the real error message and the status message, "Please wait while scripts are loaded.." will no longer appear. Now you can actually concentrate on solving the real error.

Note: Do not forget to remove this line of code once you fix everything.



Friday, December 16, 2011

Hide columns in List forms

Some times, where there is a list having many columns. We want to display only selected columns in Newform.aspx and Editform.aspx. Here is the simple way to achieve it by using Javascript.

Go to Newform.aspx and by clicking Site Actions Button, you can see that, Edit Page option is not available. There is a small work around for this to make the page editable.
Go to the address bar where the url is like /Lists/<ListName>/Newform.aspx

Append the url with ?toolpaneview=2 i.e now the url becomes

/Lists/<ListName>/Newform.aspx?toolpaneview=2.  and click enter.

Now the page will be in editable format and you can add additional Webparts to it.

Add a CEWP and edit the source and include the following script


<script language="javascript" type="text/javascript">_spBodyOnLoadFunctionNames.push("hideFields");function hideFields()
{
   var control = getTagFromIdentifierAndTitle("Input","TextField",<column name>);
   control.parentNode.parentNode.parentNode.style.display=
"none";
}

function getTagFromIdentifierAndTitle(tagName, identifier, title)
{
   var len = identifier.length;
   var tags = document.getElementsByTagName(tagName);
   for (var i=0; i < tags.length; i++)
   {
      var tempString = tags[i].id;
      if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len))
        {
         return tags[i];
         }
    }
   return null;
}
</script>


The script above will hide the column with name specified as a third argument.
The first argument for the function getTagFromIdentifierAndTitle is the type of control, second one states the field type of Sharepoint.

As per the above example the column which is made hidden is of Type Single line of text. The control rendered would be a html input control and the field type is Text Field.


The control would be found by this function. But as we have to hide the entire row, we will reach the <tr> element by accessing the parentNode for the control.

Usually in the list form, if you observe the source of the page, the controls are rendered as follows





<TR>
         <TD nowrap="true" valign="top" width="190px" class="ms-formlabel"><H3 class="ms-standardheader">
         <nobr>Tag No</nobr>
</H3></TD>
         <TD valign="top" class="ms-formbody" width="400px">
         <!-- FieldName="Tag No"
                 FieldInternalName="TagNo"
                 FieldType="SPFieldText"
           -->
                <span dir="none">
         <input name="ctl00$m$g_d9e24359_564a_4eef_941e_b15de04de81f$ctl00$ctl04$ctl00$ctl00$ctl00$ctl04$ctl00$ctl00$TextField" type="text" maxlength="255" id="ctl00_m_g_d9e24359_564a_4eef_941e_b15de04de81f_ctl00_ctl04_ctl00_ctl00_ctl00_ctl04_ctl00_ctl00_TextField" title="Tag No" class="ms-long" /><br>
</span>
               
               
         </TD>
</TR>


The control is embed inside a Span tag and which is inside the <TD> element.
There fore in order to reach the <tr> element, we have to go 3 levels up.

control.parentNode.parentNode.parentNode this point to the entire row. and now we can make it hidden.


Find below the list of the controls rendered for different field types of Sharepoint


Single Line of Text
TextField
input
Multiple Lines of Text
TextField
input
Number
TextField
input
Currency
TextField
input
Choice (dropdown)
DropDownChoice
select
Lookup (single)*
Lookup
select
Lookup (multiple)
SelectCandidate; SelectResult       
select
Yes/No
BooleanField
input



Like wise you can hide other controls also.
But the rendering of each field type differs.
For e.g take a Multiple lines of text column. This renders as text area but the emdedding would be as follows

<TR>
  <TD nowrap="true" valign="top" width="190px" class="ms-formlabel"><H3 class="ms-standardheader">
      <nobr>Comments</nobr>
    </H3></TD>
<TD valign="top" class="ms-formbody" width="400px">
    <span dir="none">
<span dir="ltr">
        <textarea name="" rows="6" cols="20" id="" title="Comments" class="ms-long" dir="none">
        </textarea>
</span>
</span>

</TD>
</TR>

The text area embeds inside 2 span tags there fore we have to add an additional parentNode element to access the entire row. Now it becomes as follows

var control = getTagFromIdentifierAndTitle("Input","TextField","Comments");
 control.parentNode.parentNode.parentNode.parentNode.style.display="none";

Will come up with another series for other types and the display form.

Happy coding!!

Thursday, December 15, 2011

Useful Sharepoint Javascript Functions


The init.js and core.js JavaScript files in the layouts directory of SharePoint 2007 contain a lot of helpful JavaScript functions. Here is a brief list of some of the most helpful classes, functions and variables available.

function TrimSpaces(str)
This function can be to trim spaces on a string.
Location
init.js

Parameters
str
  A string that will be trimmed.
Return valueThe trimmed string.

Example
var trimmed = TrimSpaces(" string with spaces "); // Returns "string with spaces".
function TrimWhiteSpaces(str)
This function can be to trim whitespaces on a string, that is spaces, tabs and linebreaks (\t \n \r \f).
Location
init.js

Parameters
str
   A string that will be trimmed.
Return valueThe trimmed string.
Examplevar trimmed = TrimWhiteSpaces("\t\tstring with spaces\n");  // Returns "string with spaces".
function escapeProperly(str)
This function takes a string and returns a URL-encoded string.
Location
init.js

Parameters
str
   A string that will be encoded.
Return valueThe encoded string.
Examplevar urlEncodedValue = escapeProperly("My Value"); // Returns "My%20Value".
function unescapeProperly(str)
This function takes a URL-encoded string and returns an string.
Location
init.js

Parameters
str
   A string that will be decoded.
Return valueThe string.
Examplevar urlDecodedValue = unescapeProperly("My%20Value"); // Returns "My Value".
class JSRequest
The JSRequest object provides parsing of the querystring, you can easily use this object to get querystring variables, filenames and pathnames. 
Location
init.js

ExampleJSRequest.EnsureSetup();
// The current url in this example is http://localhost/pages/default.aspx?debug=true
var debug = JSRequest.QueryString["debug"]; // Returns 'true'.var fileName = JSRequest.FileName; // Returns
'default.aspx'.var pathName = JSRequest.PathName; // Returns '/pages/default.aspx'.

function LoginAsAnother(url, bUseSource)
This function can be to change the current user.

Location
init.js

Parameters
url
   A string that contains url to go to after the login.
bUseSource
   A boolean that indicates that the source will be added to the url, otherwise the source will be the window.location.href. This parameter is optional, default is false.

Example

<a href="#" onclick="javascript:LoginAsAnother('\u002f_layouts\u002fAccessDenied.aspx?loginasanotheruser=true', 0)">Log on as a different user</a>

function GetUrlKeyValue(kenName, bNoDecode, url)
This function can be used to get a querystring parameter.
Location
init.js
Parameters
keyName
   A string that contains the name of the parameter.
bNoDecode
   A boolean that states whether the value has will not be encoded, this parameter is optional, default is false.
url
   A string that contains the url to fetch the querystring parameters from, this is optional, the window.location.href will be used if the parameter is null.
Return value
The value of the parameter, encoded if bNoDecode was false.
Example
var action = GetUrlKeyValue('action');


variable L_Menu_BaseUrl
This variable contains the base URL of the current site or subsite. 
Location
Inline

Exampledocument.location = L_Menu_BaseUrl + 'Lists/Tasks/AllItems.aspx';
variable L_Menu_LCID
This variable contains the LCID setting of the current site.
Location
Inline
variable L_Menu_SiteTheme
This variable contains the theme name of the current site.
LocationInline
variable _spUserId
This variable contains the id of the current user.
Location
Inline