Tuesday, April 22, 2008

Setting a default value for SharePoint Audience Targetting field

I did come across a need to set a default value for Target Audience field for a document library.

I have developed a the client-site solution that actually works with templates (won't crash if implemented using a Site Template). It will add a default value to the form field, will run the check names functions and this will only happen if there is no value already present in the field.

The tricky part is the way it looks for the field on the web page. In this case, the code is looking for the second form field that has type of TextArea, apparently it is only used for the fields that has Name Check button next to them. I had one form field for Owners and this was the second one. Find your position and update the corresponding integer in the code.

For the document library, you want to set a default Target Audience value, look for EditForm.aspx file using SharePoint Office Designer. Open this file for editing and look for following code (that in my case was at line 67):


<script id="onetidPageTitleAreaFrameScript">

document.getElementById("onetidPageTitleAreaFrame").className="ms-areaseparator";


After this line, before the closing script tag, add the following lines of javascript code:

function
withDollar(inputStr)


{

var outputStr =
"";

var guidValue =
inputStr.match(/_([0-9a-fA-F]){8}_([0-9a-fA-F]){4}_([0-9a-fA-F]){4}_([0-9a-fA-F]){4}_([0-9a-fA-F]){12}/)[0];

outputStr =
inputStr.replace(/(\{{0,1}_([0-9a-fA-F]){8}_([0-9a-fA-F]){4}_([0-9a-fA-F]){4}_([0-9a-fA-F]){4}_([0-9a-fA-F]){12}\}{0,1})/g,"[GUID]")

outputStr = outputStr.replace(/\_/g,"$");
outputStr = outputStr.replace(/\[GUID\]/,guidValue);
return
outputStr;

}
var
lastCheckboxID = 0;

var elem =
document.getElementById('aspnetForm').elements;

for(var
i = 0; i < elem.length; i++)

{
if
(elem[i].type == "textarea")
{

lastCheckboxID++;
if
(lastCheckboxID == 2) {
// 2 for
second TextArea textbox in this form, change it according to your position...

if
(elem[i].previousSibling.innerText ==

""
) {

elem[i].previousSibling.innerText="Default Value for Audience Field";
// Default Value you want to set

var
TargetAud_idStr =
elem[i].parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.id;
var arg=getUplevel(TargetAud_idStr);
var ctx=TargetAud_idStr;
EntityEditorSetWaitCursor(ctx);
WebForm_DoCallback(withDollar(TargetAud_idStr),arg,EntityEditorHandleCheckNameResult,ctx,EntityEditorHandleCheckNameError,true);
}

}
}
}

With best of luck!

Please leave feedback... thanks!

-Naveed

Thursday, May 17, 2007

URL

Please visit: www.numerictrust.com. The company is out of business though :(