Monthly Archives: September 2013

Pre-Populate SharePoint Form Fields

In this article, I’m excited that I found a brilliant article to Pre-Populate SharePoint form fields in your Library or List NewForm.aspx or EditForm.aspx using jquery.
The great thing, it also works for Rich Text, Numbers, Dates, Date/Time, People, and Choice/Lookup. Thanks to Paul Grenier …

prepopulateformfields

You could find more detail information from reference link below. But long story short, include CEWP that contains below script to your NewForm.aspx or EditForm.aspx

<script type="text/javascript">// <![CDATA[
//?PageView=Shared&ToolPaneView=2
if(typeof jQuery=="undefined"){
	var jQPath="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/";
	document.write("<script src='",jQPath,"jquery.min.js' type='text/javascript'><\/script>");
}
// ]]></script>
<script type="text/javascript">// <![CDATA[
/*
 * Prepopulate form fields in SharePoint
 * Copyright (c) 2008 Paul Grenier (endusersharepoint.com)
 * Licensed under the MIT (MIT-LICENSE.txt)
 */
(function(){
	var params = window.location.search.substring(1).split("&"),
		kv = {},
		opts,
		sp=/%20|\+/g,
		datetime=/([1-9]|0[1-9]|1[012])[\-\/.]([1-9]|0[1-9]|[12][0-9]|3[01])[\-\/.](19|20)\d\d\s([0-1][0-2]|[0-9]):([0-9]{2})\s(A|P)M/i,
		date=/([1-9]|0[1-9]|1[012])[\-\/.]([1-9]|0[1-9]|[12][0-9]|3[01])[\-\/.](19|20)\d\d/,
		clean = function(str){
			return str.replace(sp," ");
		},
		getKv = function(){
			$.each(params,function(i,e){
				var p=e.split("=");
				kv[p[0]]=decodeURIComponent(p[1]);
			});
			return kv;
		};
	jQuery.prepop = function(){
		$.each(getKv(),function(k,v){
			k=clean(k);
			v=clean(v);
			var f=$("[title='"+k+"']"),
				job;
			if (f.length>0){
				if (f[0].type=="text"){job=10;} //text
				if (f[0].type=="checkbox"){job=20;} //checkbox
				if (f[0].tagName=="SPAN"&&f.hasClass("ms-RadioText")){job=30;} //radio
				if (f[0].type=="select-one"&&f[0].tagName=="SELECT"){job=10;} //choice and non-IE lookup
				if (f[0].tagName=="TEXTAREA"){job=10;} //textarea
				if (f[0].type=="text"&&f[0].opt=="_Select"){job=70;} //IE lookup
				if (v.match(date)){job=40;} //date
				if (v.match(datetime)){job=50;} //datetime
			}
			if (f.length===0){
				var elm = $("nobr:contains('"+k+"')");
				if (elm.length>0){
					elm = elm.parents("td").next()[0];
					var s1 = $(elm).find("select:first"),
						s2 = $(elm).find("select:last"),
						p1 = $(elm).find("textarea[title='People Picker']"),
						p2 = $(elm).find("div[title='People Picker']"),
						vals = v.split(",");
					if (s1.length>0){job=80;} //multi-select
					if (p1.length>0){job=90;} //people picker
				}
			}
			switch (job){
			case 10:
				if (v.substring(0,1)=="@"){
					opts = f[0].options;
					$.each(opts,function(i,e){
						if (opts[i].value==v.substring(1)){f[0].selectedIndex=i;}
					});
				}else{
					f.val(v);
				}
				break;
			case 20:
				if (v.toUpperCase()=="TRUE"||v=="1"){f[0].checked=true;}
				if (v.toUpperCase()=="FALSE"||v=="0"){f[0].checked=false;}
				break;
			case 30:
				if (v.toUpperCase()=="TRUE"||v=="1"){f.find("input:radio").click();}
				break;
			case 40:
				v=v.replace(/[\-\/.]/g,"/");
				f.val(v);
				break;
			case 50:
				var dt=v.split(" "),
					d=dt[0].replace(/[\-\/.]/g,"/"),
					t=dt[1],
					hm=t.split(":"),
					hh=hm[0].replace(/^0/,""),
					mm=hm[1],
					ap=dt[2].toUpperCase();
				f.val(d);
				f.parent("td").siblings("td.ms-dttimeinput")
					.find("select:first").val(hh+" "+ap)
					.parent("td").find("select:last").val(mm);
				break;
			case 70:
				if (v.substring(0,1)=="@"){
					ShowDropdown(f[0].id);
					opts = $("#_Select")[0].options;
					$.each(opts,function(i,e){
						if (opts[i].value==v.substring(1)){$("#_Select")[0].selectedIndex=i;}
					});
					f.blur();
				}else{
					f.val(v);
					ShowDropdown(f[0].id);
					f.blur();
				}
				break;
			case 80:
				opts = s1[0].options;
				$.each(vals,function(i,e){
					var V=e;
					$.each(opts,function(i,e){
						if (opts[i].text==V){
							s2.append("
<option value='"+opts[i].value+"'>"+V+"</option>

");
						}
						if (V.substring(0,1)=="@"){
							if (opts[i].value==V.substring(1)){
								s2.append("
<option value='"+V+"'>"+opts[i].text+"</option>

");
							}
						}
					});
				});
				break;
			case 90:
				var p=vals.join(";");
				p1.val(p);
				p2.html(p);
				break;
			//default:
			}
		});
	};
})();
$(function(){
	$.prepop();
});
// ]]></script>

Reference

https://www.nothingbutsharepoint.com/sites/eusp/pages/jquery-for-everyone-pre-populate-form-fields.aspx

Advertisements

Add webpart to SharePoint default NewForm.aspx, EditForm.aspx or DisplayForm.aspx

This is simple trick to add OOTB webpart or custom webpart to SharePoint default form.aspx in your SharePoint List or Document Library.

Pass below url parameters after .aspx

?PageView=Shared&ToolPaneView=2

This will change the page in edit mode where you could see the webpart zone to add other webpart.
Once you’ve completed your update, just save the page.
Then you will have the option to edit the page from Site Actions later on.

The Right Format for CDATA inside CDATA

Recently, I would like to include Content Editor webpart into a page through feature. I also would like to initialized my javascript into the CEWP.

Initially, I have my CEWP added to the page manually and edit the webpart source to include my javascript, everything looks good. Export the webpart and include the exported xml into file element in element.xml. I found out there is CDATA tag inside the outer CDATA tag. This makes my outer CDATA tag broken. Its like you need escape characters in a string, if you know what I mean.

I spent a bit of time to look for the solution, probably because I do not search the right keyword in google. Anyway the valid format would be:

From

<![CDATA[ blah blah blah <![CDATA[ bleh bleh bleh ]]> blah blah blah ]]>

To

<![CDATA[ blah blah blah <![CDATA[ bleh bleh bleh ]]]]><![CDATA[> blah blah blah ]]>

My full file element would be:

    <File Url="Account.aspx" Type="GhostableInLibrary" IgnoreIfAlreadyExists="TRUE" >
      <Property Name="Title" Value="Account page." />
      <Property Name="UIVersion" Value="4" />
      <Property Name="ContentType" Value="$Resources:cmscore,contenttype_pagelayout_name;" />
      <Property Name="PublishingPreviewImage" Value="$PublishingPreviewImage$" />
      <Property Name="PublishingPageLayout" Value="~SiteCollection/_catalogs/masterpage/CustomPageLayout.aspx, My Custom Page Layout "/>
      <Property Name="PublishingAssociatedContentType" Value=";#$Resources:cmscore,contenttype_articlepage_name;;#0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D;#"/>
      <AllUsersWebPart WebPartZoneID="Top" WebPartOrder="1">
        <![CDATA[              
        <?xml version="1.0" encoding="utf-8"?>
          <WebPart xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/WebPart/v2">
            <Title>Content Editor</Title>
            <FrameType>Default</FrameType>
            <Description>Allows authors to enter rich text content.</Description>
            <IsIncluded>true</IsIncluded>
            <ZoneID>Top</ZoneID>
            <PartOrder>1</PartOrder>
            <FrameState>Normal</FrameState>
            <Height />
            <Width />
            <AllowRemove>true</AllowRemove>
            <AllowZoneChange>true</AllowZoneChange>
            <AllowMinimize>true</AllowMinimize>
            <AllowConnect>true</AllowConnect>
            <AllowEdit>true</AllowEdit>
            <AllowHide>true</AllowHide>
            <IsVisible>false</IsVisible>
            <DetailLink />
            <HelpLink />
            <HelpMode>Modeless</HelpMode>
            <Dir>Default</Dir>
            <PartImageSmall />
            <MissingAssembly>Cannot import this Web Part.</MissingAssembly>
            <PartImageLarge>/_layouts/15/images/mscontl.gif</PartImageLarge>
            <IsIncludedFilter />
            <Assembly>Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
            <TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>
            <ContentLink xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor" />
            <Content xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor"><![CDATA[
            <script>
              function HideAllChildDiv()
              {
               $('#Account1').hide();
               $('#Account2').hide();
               $('#Account3').hide();
              }
              
              HideAllChildDiv();
              $('#Account1').show();
            </script>
          ]]]]><![CDATA[>
          </Content>
          <PartStorage xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor" />
          </WebPart>
          ]]>

      </AllUsersWebPart>
    </File>
%d bloggers like this: