Tuesday, April 28, 2009

Getting Current User and setting it to the People Picker using JavaScript

//Set People picker field to current user by Andy Bonner

_spBodyOnLoadFunctionNames.push("fillDefaultValues");



function fillDefaultValues()

{

fillPeoplePickerWithCurrentUser('Submitted_x0020_By');

}



function fillPeoplePickerWithCurrentUser(pickerName)

{

//get the current user from the welcome menu
var currentUser = getCurrentUser();
//check to see that we've got it
if(currentUser != null)
{
//get the people pickers input div
var pp = getPickerInputElement(pickerName);
//set it to the current user if we've found it
if(pp != null)
pp.innerHTML = currentUser;

}

}


function getCurrentUser()
{
var tags = document.getElementsByTagName('a');
for (var i=0; i < tags.length; i++)
{
if(tags[i].innerText.substr(0,7) == 'Welcome')
{
return tags[i].innerText.substr(8,tags[i].innerText.length);
}
}
}


function getPickerInputElement(fieldsInternalName)
{
var result = "";
var divs = document.getElementsByTagName("DIV");
for(var i=0; i < divs.length ; i++)
{
if(divs[i].id=="WebPartWPQ2")
{
var tds = divs[i].getElementsByTagName("TD");
for(var j=0; j < tds.length; j++)
{
var cellHTML = tds[j].innerHTML;
if(cellHTML.indexOf('FieldInternalName="' + fieldsInternalName + '"') >= 0)
{
var innerDivs = tds[j].getElementsByTagName("DIV");
for(var k=0; k < innerDivs .length; k++)
{
if(innerDivs[k].id.indexOf("UserField_upLevelDiv") > 0)
{
result = innerDivs[k];
break;
}
}
}
}
}
}
return result;
}

JavaScript funtion to hide fields on Newform.aspx/Editform.aspx

•TAGNAME: HTML element that is being rendered ("SELECT", "INPUT"...)

•IDENTIFIER: SharePoint field type identifier ("TextField", "DropDownChoice"...)

•FIELD NAME: Display name of the field (e.g. "Status", "Customer Name"...)



Script starts...


_spBodyOnLoadFunctionNames.push("hideFields");

function hideFields() {
var control = getTagFromIdentifierAndTitle("TAGNAME","IDENTIFIER","FIELD 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 ends...

you can also refer to this link

Monday, April 27, 2009

JavaScripts to Disable controls on Newform.aspx/Editform.aspx

JavaScripts to Disable controls on Editform.aspx


for(var i = 0; i < document.aspnetForm.elements.length; i++)
if ((document.aspnetForm.elements[i].title == "Recommendation")) // give the title of the control that you want to disable
{
document.aspnetForm.elements[i].disabled =
true;
}

JavaScript function to get element using tag name and title

function GetElementByText(tagName, title)
{
var a = document.getElementsByTagName(tagName);

for (var i=0; i < a.length; i++)
{
if (a[i].value)
{
if (a[i].value == title )
{
return a[i];
}
}
}
return null;
}

Add Custom Menu to List Item and Document Library Item

var siteUrl = GetSiteUrl();

function Custom_AddListMenuItems(m, ctx)
{
var copyCurrentItemId = currentItemID;
var titleText = null;

// Add Open Workspace menu item
var strDisplayText = "Request Home";
var strAction = "document.location.href='"+siteUrl+"/DCP/RequestPage.aspx?Request="+titleText+"&ID="+copyCurrentItemId+"'";
CAMOpt(m, strDisplayText, strAction);
CAMSep(m);


// false means that the standard menu items should also rendered

return false;
}

function me()
{
window.location = siteUrl + "/DCP/NewRequestByMgr.aspx?&Source="+GetSource();
}

function GetSiteUrl()
{
var siteUrl = window.location.href;
var copyOfSiteUrl = siteUrl;
siteUrl = siteUrl.split("/");
var isSubSite = false;
var url = null;

if(siteUrl[3] == 'sites')
{
isSubSite = true;

}
if(isSubSite)
{
copyOfSiteUrl = copyOfSiteUrl.split("sites/");
var subSiteName = copyOfSiteUrl[1].split("/");
url = copyOfSiteUrl[0] + "sites/" + subSiteName[0];
return url;
}
else
{
copyOfSiteUrl = copyOfSiteUrl.split("/");
url = copyOfSiteUrl[0] + "//" + copyOfSiteUrl[2];
return url;
}
}


For document library use
function AddDocLibMenuItems(m, ctx)
{
if (typeof(Custom_AddDocLibMenuItems) != “undefined”)
{
if (Custom_AddDocLibMenuItems(m, ctx))
return;
}
}
function instead of Custom_AddListMenuItems(m, ctx)
{
.....
}

Filtered Lookup Lists in SharePoint

SharePoint allows you to create custom lists with your own custom columns. One type you can use for these columns is a lookup against one of your other lists in the SharePoint site. By default this lookup gives the user all the items that are available in the list. Many times, you probably want to have a filtered list instead of the complete one.
Lately, I had to do exactly this for a customer. The approach explained here is probably not the only one you can take but it is one you can start with and it is not difficult to incorporate that within your NewForm/EditForm.aspx (the pages where you actually see the lookup). The approach I have taken is a small JavaScript function that repopulates the dropdown based on the items in the lookuplist that are visible via a view you create. Take for example a list that allows users to submit questions to SharePoint. Besides columns for capturing data regarding the question itself, the user also has to select the person who has to handle the question. In our case, the person submitting the question has one or more roles he or she can select from. A custom list storing this information is create to support the lookup that needs to be done.
When you create the Questions list, you can create a column Role that points to that second lookup list. Problem is that everything out of that list is displayed to the user and we want to have the user only see those entries that are relevant for him or her. So, I first thing I did was to create a new view on the second list that only displays all the roles for the logged on user. This view has the filter set to [Me] (a common practice when creating views).
Next thing you do is to open up the EditForm.aspx of the first list (the questions one) in FrontPage. At the bottom of the HTML (just before the closing BODY tag) you can add the following script blocks.


The first block points to a Javascript file with a generic function to repopulate lists (note that it needs more exception handling to become really generic!). Here is the content of that file:

function RepopulateList(controlName,siteName,lookupListName,lookupViewName,textField,valueField) { // -- retrieve the list for the elements var listEl = document.getElementsByName(controlName) // -- emptying the listif(listEl.length>0) { listEl(0).innerHTML = ""; // -- getting the filtered lookup var reqstring = siteName + "/_vti_bin/owssvr.dll?CS=109&XMLDATA=1&RowLimit=0&List=" + lookupListName + "&View=" + lookupViewName; var req = new ActiveXObject("MSXML2.XMLHTTP"); req.open("GET",reqstring,false); req.send(); // -- loading response in XML Document var doc = new ActiveXObject("MSXML2.DOMDocument"); doc.loadXML(req.responseText); var data = doc.documentElement.childNodes(1); for (i=0;i

The second script block calls this function providing it the necessary values to go back to the server and retrieve the XML with only the data provided by the created view. I use that XML to repopulate the list then. Notice the owssvr.dll I am calling in the script. When you look at a view in a SharePoint, you can always view the source of that page and at the bottom of the page you will find the following information: You can copy this link and run it in the browser. The result is the following: This is the response I need to repopulate the dropdown then with only the roles for the current visitor. The performance is not that great if you apply this technique for big lookup lists so be careful. Test it first for your own specific scenario. To filter big lookup lists, you better have a look at your own custom ASP.NET control.

You can refer to this link as well

JavaScript Funtions to get Query String Value, Host Name and Site Url

function GetQueryString( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
{
if(results[1].indexOf('+')!= '-1')
{
results = results[1].replace('+',' ');
return results;
}
if(results[1].indexOf('%')!= '-1')
{
results = results[1].replace('%20',' ');
return results;
}
else
return results[1];

}
}


function getHost()
{
var url = window.location;
var urlparts = url.split('/');
var host = urlparts[0];
return host;
}

function GetSiteUrl()
{
var siteUrl = window.location.href;
var copyOfSiteUrl = siteUrl;
siteUrl = siteUrl.split("/");
var isSubSite = false;
var url = null;

if(siteUrl[3] == 'sites')
{
isSubSite = true;

}
if(isSubSite)
{
copyOfSiteUrl = copyOfSiteUrl.split("sites/");
var subSiteName = copyOfSiteUrl[1].split("/");
url = copyOfSiteUrl[0] + "sites/" + subSiteName[0];
return url;
}
else
{
copyOfSiteUrl = copyOfSiteUrl.split("/");
url = copyOfSiteUrl[0] + "//" + copyOfSiteUrl[2];
return url;
}
}

PreSaveAction to EditForm.aspx

The creators of that script added a “hook” for custom validation called PreSaveAction. This function gets called during the submit action but was never defined so we can create our own. We have a simple strategy: identify Tasks surfaced through our Linked Tasks web part and stop the submit action if Issue status = ‘Closed’ and number of Tasks > 0. Translating that “simple” logic into javascript takes patience and testing. Add the PreSaveAction to the EditForm.aspx page

Sample Event Handler to set Permissions

This is something I have been seeing the need for in the forums for quite some time, and today I found an hour to find this. A request is often made to have an event handler that automagically sets the permissions on a list item so that only the author of the item can edit it, while other people with contributor permissions on the library can only read it.Sometimes the logic is more complex, but I think this sample code should be enough to get anyone started!

Creating & Adding Event Handler

In this article, author has create an event handler that captures the events of the document library and add an entry in the cell of the document added. It can add an event handler using code or as a feature. In order to write an event handler, we will first create a sharepoint site and create a document library. We will, then, capture the events of the document library.