Monday 30 July 2012

Generate DropDown values in EditForm of Library at runtime

If we want to generate values in one dropdown field dynamically in the EditForm.aspx of Library comparing to some value in other list.

Here in the following example we create a list having Username & Department columns.

Also create a library having the SubDepartment field as dropdown field which should show values according to the department of the current user in UsersDepartment list.


 <script runat="server">
protected void Page_Load(Object sender, EventArgs e)
{
   SPSecurity.RunWithElevatedPrivileges(delegate()
   {
      // Elevated Permission Code Goes Here
      using (SPSite spSite = SPContext.Current.Site)
      {
        using (SPWeb web = spSite.OpenWeb())
        {

           //Read List & Library
           SPList DepartmentList = web.Lists["UsersDepartment"];

           SPList MyDocumentList = web.Lists["MyDocumentLibrary"];
           //Read SubDepartment field from Library
           SPFieldChoice choicefield = (SPFieldChoice)
MyDocumentList.Fields["SubDepartment"];
           SPQuery query = new SPQuery();

           //Get Current User  
               SPUser currentuser =SPContext.Current.Web.CurrentUser;
               string strcurrentuser = currentuser.LoginName.ToString();
               char[] arrSplit={'\\'};
               query.Query = @"<Where><Eq><FieldRef Name='User_x0020_Name'  /><Value Type='Text'>" + strcurrentuser.Split(arrSplit)[1] + @"</Value></Eq></Where>";
           //Fetch listitems from DepartmentList
               SPListItemCollection collListItem = DepartmentList.GetItems(query);
                web.AllowUnsafeUpdates = true;
               if(collListItem.Count > 0)
               {
                 string department =collListItem[0]["Department"].ToString();
               if(department !="")
              {
                if(department == "Science")
                {
                  choicefield.Choices.Clear();
                  choicefield.Choices.Add("Select Department");
                  choicefield.Choices.Add("Physics");

                  choicefield.Choices.Add("Chemistry");
                  choicefield.Choices.Add("Biology");
                  choicefield.Hidden=false;
                  choicefield.Required=true;
                  choicefield.Update();
                }
                else if
(department == "Commerce")
                  choicefield.Choices.Clear();
                  choicefield.Choices.Add("Select Department");
                  choicefield.Choices.Add("Accounts");
                  choicefield.Choices.Add("Marketing");
                  choicefield.Hidden=false;
                  choicefield.Required=true;
                  choicefield.Update();
                }
              }
                else
                {
                   choicefield.Hidden=true;
                   choicefield.Required=false;
                   choicefield.Update();
                }
              }
              else
              {
                 choicefield.Hidden=true;
                 choicefield.Required=false;
                 choicefield.Update();
        }
         
MyDocumentList.Update();
          web.AllowUnsafeUpdates = false;
      }
    }
  });
 }
  </script>






In the above code if the department of the current user is "Science" the values populated in the dropdown will be "Physics", "Chemistry" & "Biology".

This code runs at server side.

Copy the above code on the page where the above document library is rendered using SharePoint Designer.




 

Hide List columns in EditForm & DisplayForm at RunTime


Scenario 1:
If the Administrator does not want to allow end users to see all columns in default EditForm or DisplayForm of a list then he can hide the specific columns from end users by using the following script

<script type="text/javascript">
$(document).ready(function(){
     $('nobr:contains("Column-Name1")').closest('tr').hide();
     $('nobr:contains("Column-Name2")').closest('tr').hide();
});</script>

where Column-Name1is the name of the column within the list which the administrator wants to hide.

Scenario 2:
If the Administrator wants to hide certain columns based on the value of other column within the list from end users in default EditForm or DisplayForm of a list then he can hide the specific columns by using the following script

<script type="text/javascript">
$(document).ready(function(){
     var DropDownStatus = $("[title='Status']").val();
     if(DropDownStatus == "Pending")
     {
         $('nobr:contains("ColumnToHide")').closest('tr').hide();
     }
});</script>



where,

ColumnToHide is the name of the column within the list which the administrator wants to hide.

 var DropDownStatus = $("[title='Status']").val(); - fetches the value of the column name "Status" & assigns it to variable DropDownStatus.



Sunday 29 July 2012

Change the Name Survey in "Respond to this Survey"

We can change the Name Survey in "Respond to this Survey", "Survey Name" "Survey Description" to some other name using javascript.

In the following example I'll change the name to the Quiz

Following is the script to achieve the same.

<script type="text/javascript">
$(document).ready(function() {
$('[title]').removeAttr('title');
changespantext();
changeName();
});
function changespantext()
{
  var spans = document.getElementsByTagName("span");
    for(var i=0;i<spans.length; i++)
   {
    if(spans[i].innerHTML == "Respond to this Survey")
     {  //is this the "Respond to this Survey" span?
        spans[i].innerHTML = "Respond to this Quiz";  

        //change to new value
         break; 

       //hop out of the loop, we're done
     }
   }
}
function changeName()
{

   var tdid= document.getElementById("overview01");
   var tdid1= document.getElementById("overview02");

   tdid.innerHTML="Quiz Name:";
   tdid1.innerHTML="Quiz Description:";
}
 </script>




Hide Graphical Summary & Show all responses links in Survey

Following is the script to hide the Show a graphical summary of responses & Show all responses link in Survey overview page as shown in screenshot.



<script type="text/javascript">
_spBodyOnLoadFunctionNames.push("hideanchor");
_spBodyOnLoadFunctionNames.push("changeiMageblank");
_spBodyOnLoadFunctionNames.push("changeiMageblank1");

function hideanchor()
{     
  var anchort= document.getElementById("diidSurveyResults");
  var anchort1= document.getElementById("diidResultsByUser");
  anchort.style.display = 'none';
  anchort1.style.display = 'none';   
}
function changeiMageblank()
{
 var inputs = document.getElementsByTagName("img");
 for(i = 0; i<inputs.length; i++)
 {
  if(inputs[i].getAttribute("src").indexOf("/_layouts/images/rect.gif") != -1)
    {
      inputs[i].parentNode.removeChild(inputs[i]);
    }
 }
}
function changeiMageblank1()
{
 var inputs = document.getElementsByTagName("img");
 for(i = 0; i<inputs.length; i++)
 {
  if(inputs[i].getAttribute("src").indexOf("/_layouts/images/rect.gif")!= -1)
    {
    inputs[i].parentNode.removeChild(inputs[i]);
    }
 }
} 
</script>

Add the above code in the CEWP of the page where the survey overview is rendered.

hideanchor Function hides the hyperlinks 
changeiMageblank Function removes the images

Hide Survey Toolbar

Script to hide the Actions & Settings Menu in Survey toolbar.
       
Insert the following script in CEWP of the page where the survey overview is displayed.


<script>
      function HideDiv(name) { 
           var div = document.getElementsByTagName('div'); 
           for (var i = 0; i < div.length; i++) { 
              var str = div[i].id; 
              if (str.indexOf(name) >= 0) { 
                  var viewInExplorer = div[i]; 
                  if (viewInExplorer != null) { 
                      if (viewInExplorer.parentNode != null) 
                          viewInExplorer.parentNode.removeChild(viewInExplorer); 
                  } 
              } 
          } 

      } 
      HideDiv("ListActionsMenu"); 
      HideDiv("ListSettingsMenu"); 
  </script>

       

Align Survey Radio Buttons horizontally


Using jquery to align the radio buttons in survey horizontally in SharePoint 2010.

Pre-requisites:
We need the following jquery libraries: 
1) jquery-1.7.2.min.js
2) jquery.SPServices-0.7.1a.min.js

Download the above jquery libraries & save them in your site.
Open the Survey NewForm.aspx page in browser & add the following script in the CEWP.

<script type="text/javascript" src="LocationPath/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="LocationPath/jquery.SPServices-0.7.1a.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$().SPServices.SPArrangeChoices({

    columnName:"Radio Button",
    perRow:3
});

$().SPServices.SPArrangeChoices({
    columnName:"Radio Button 2",
    perRow:5
});

});
</script>
 

where,
columnName: Refers to the display name of the column
perRow: Represents number of radio buttons to be displayed on each row. 
Note: Highest number of radio buttons that can be displayed in one row is 99.


Saturday 28 July 2012

DateTime.ToString() Patterns

 

All the patterns:

0
MM/dd/yyyy
08/22/2006
1
dddd, dd MMMM yyyy
Tuesday, 22 August 2006
2
dddd, dd MMMM yyyy
HH:mm Tuesday, 22 August 2006 06:30
3
dddd, dd MMMM yyyy
hh:mm tt Tuesday, 22 August 2006 06:30 AM
4
dddd, dd MMMM yyyy
H:mm Tuesday, 22 August 2006 6:30
5
dddd, dd MMMM yyyy
h:mm tt Tuesday, 22 August 2006 6:30 AM
6
dddd, dd MMMM yyyy HH:mm:ss
Tuesday, 22 August 2006 06:30:07
7
MM/dd/yyyy HH:mm
08/22/2006 06:30
8
MM/dd/yyyy hh:mm tt
08/22/2006 06:30 AM
9
MM/dd/yyyy H:mm
08/22/2006 6:30
10
MM/dd/yyyy h:mm tt
08/22/2006 6:30 AM
10
MM/dd/yyyy h:mm tt
08/22/2006 6:30 AM
10
MM/dd/yyyy h:mm tt
08/22/2006 6:30 AM
11
MM/dd/yyyy HH:mm:ss
08/22/2006 06:30:07
12
MMMM dd
August 22
13
MMMM dd
August 22
14
yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK
2006-08-22T06:30:07.7199222-04:00
15
yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK
2006-08-22T06:30:07.7199222-04:00
16
ddd, dd MMM yyyy HH':'mm':'ss 'GMT'
Tue, 22 Aug 2006 06:30:07 GMT
17
ddd, dd MMM yyyy HH':'mm':'ss 'GMT'
Tue, 22 Aug 2006 06:30:07 GMT
18
yyyy'-'MM'-'dd'T'HH':'mm':'ss
2006-08-22T06:30:07
19
HH:mm
06:30
20
hh:mm tt
06:30 AM
21
H:mm
6:30
22
h:mm tt
6:30 AM
23
HH:mm:ss
06:30:07
24
yyyy'-'MM'-'dd HH':'mm':'ss'Z'
2006-08-22 06:30:07Z
25
dddd, dd MMMM yyyy HH:mm:ss
Tuesday, 22 August 2006 06:30:07
26
yyyy MMMM
2006 August
27
yyyy MMMM
2006 August

The patterns for DateTime.ToString ( 'd' ) :

0
MM/dd/yyyy
08/22/2006

The patterns for DateTime.ToString ( 'D' ) :

0
dddd, dd MMMM yyyy
Tuesday, 22 August 2006

The patterns for DateTime.ToString ( 'f' ) :

0
dddd, dd MMMM yyyy HH:mm
Tuesday, 22 August 2006 06:30
1
dddd, dd MMMM yyyy hh:mm
tt Tuesday, 22 August 2006 06:30 AM
2
dddd, dd MMMM yyyy H:mm
Tuesday, 22 August 2006 6:30
3
dddd, dd MMMM yyyy h:mm
tt Tuesday, 22 August 2006 6:30 AM

The patterns for DateTime.ToString ( 'F' ) :

0
dddd, dd MMMM yyyy HH:mm:ss
Tuesday, 22 August 2006 06:30:07

The patterns for DateTime.ToString ( 'g' ) :

0
MM/dd/yyyy HH:mm
08/22/2006 06:30
1
MM/dd/yyyy hh:mm
tt 08/22/2006 06:30 AM
2
MM/dd/yyyy H:mm
08/22/2006 6:30
3
MM/dd/yyyy h:mm tt
08/22/2006 6:30 AM

The patterns for DateTime.ToString ( 'G' ) :

0
MM/dd/yyyy HH:mm:ss
08/22/2006 06:30:07

The patterns for DateTime.ToString ( 'm' ) :

0
MMMM dd
August 22

The patterns for DateTime.ToString ( 'r' ) :

0
ddd, dd MMM yyyy HH':'mm':'ss 'GMT'
Tue, 22 Aug 2006 06:30:07 GMT

The patterns for DateTime.ToString ( 's' ) :

0
yyyy'-'MM'-'dd'T'HH':'mm':'ss
2006-08-22T06:30:07

The patterns for DateTime.ToString ( 'u' ) :

0
yyyy'-'MM'-'dd HH':'mm':'ss'Z'
2006-08-22 06:30:07Z

The patterns for DateTime.ToString ( 'U' ) :

0
dddd, dd MMMM yyyy HH:mm:ss
Tuesday, 22 August 2006 06:30:07

The patterns for DateTime.ToString ( 'y' ) :

0
yyyy MMMM 2006 August

Building a custom DateTime.ToString Patterns

The following details the meaning of each pattern character. Note the K and z character.
d
Represents the day of the month as a number from 1 through 31. A single-digit day is formatted without a leading zero
dd
Represents the day of the month as a number from 01 through 31. A single-digit day is formatted with a leading zero
ddd
Represents the abbreviated name of the day of the week (Mon, Tues, Wed etc)
dddd
Represents the full name of the day of the week (Monday, Tuesday etc)
h
12-hour clock hour (e.g. 7)
hh
12-hour clock, with a leading 0 (e.g. 07)
H
24-hour clock hour (e.g. 19)
HH
24-hour clock hour, with a leading 0 (e.g. 19)
m
Minutes
mm
Minutes with a leading zero
M
Month number
MM
Month number with leading zero
MMM
Abbreviated Month Name (e.g. Dec)
MMMM
Full month name (e.g. December)
s
Seconds
ss
Seconds with leading zero
t
Abbreviated AM / PM (e.g. A or P)
tt
AM / PM (e.g. AM or PM
y
Year, no leading zero (e.g. 2001 would be 1)
yy
Year, leadin zero (e.g. 2001 would be 01)
yyy
Year, (e.g. 2001 would be 2001)
yyyy
Year, (e.g. 2001 would be 2001)
K
Represents the time zone information of a date and time value (e.g. +05:00)
z
With DateTime values, represents the signed offset of the local operating system's time zone from Coordinated Universal Time (UTC), measured in hours. (e.g. +6)
zz
As z but with leadin zero (e.g. +06)
zzz
With DateTime values, represents the signed offset of the local operating system's time zone from UTC, measured in hours and minutes. (e.g. +06:00)
f
Represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value.
ff
Represents the two most significant digits of the seconds fraction; that is, it represents the hundredths of a second in a date and time value.
fff
Represents the three most significant digits of the seconds fraction; that is, it represents the milliseconds in a date and time value.
ffff
Represents the four most significant digits of the seconds fraction; that is, it represents the ten thousandths of a second in a date and time value. While it is possible to display the ten thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
fffff
Represents the five most significant digits of the seconds fraction; that is, it represents the hundred thousandths of a second in a date and time value. While it is possible to display the hundred thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
ffffff
Represents the six most significant digits of the seconds fraction; that is, it represents the millionths of a second in a date and time value. While it is possible to display the millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
fffffff
Represents the seven most significant digits of the seconds fraction; that is, it represents the ten millionths of a second in a date and time value. While it is possible to display the ten millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
F
Represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value. Nothing is displayed if the digit is zero.
:
Represents the time separator defined in the current DateTimeFormatInfo..::.TimeSeparator property. This separator is used to differentiate hours, minutes, and seconds.
/
Represents the date separator defined in the current DateTimeFormatInfo..::.DateSeparator property. This separator is used to differentiate years, months, and days.
"
Represents a quoted string (quotation mark). Displays the literal value of any string between two quotation marks ("). Your application should precede each quotation mark with an escape character (\).
'
Represents a quoted string (apostrophe). Displays the literal value of any string between two apostrophe (') characters.
%c
Represents the result associated with a c custom format specifier, when the custom date and time format string consists solely of that custom format specifier. That is, to use the d, f, F, h, m, s, t, y, z, H, or M custom format specifier by itself, the application should specify %d, %f, %F, %h, %m, %s, %t, %y, %z, %H, or %M. For more information about using a single format specifier, see Using Single Custom Format Specifiers.
||\c || Represents the escape character, and displays the character "c" as a literal when that character is preceded by the escape character (\). To insert the backslash character itself in the result string, the application should use two escape characters ("\\").
Any other character copies any other character to the result string, without affecting formatting. ||