Tuesday, June 14, 2011

Hide a required field in SharePoint list while adding new item !

There may be cases when we need to a hide required field while adding a new item to a list but at the same time you may want to show it while editing the item.

The above case looks tricky but it is easily achievable using some extra bit of code or PowerShell

C#

string siteUrl = "http://mysite";
SPSite site = new SPSite(siteUrl);
SPWeb web = site.OpenWeb();
site.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = true;
SPList list = web.Lists["mylist"];
SPField fldName = list.Fields["Name"];
fldName.ShowInNewForm = false;
fldName.Update();
list.Update();

PowerShell

[system.reflection.assembly]::loadwithpartialname("microsoft.sharepoint")
$site= New-Object Microsoft.SharePoint.SPSite ("http://d-dev1:1234/gp")
$web=$site.OpenWeb()
$list=$web.Lists["mylist"]
$field = $list.Fields["Name"]
$field.ShowInNewForm = $false
$field.Update()

If you want to hide this field in edit form, you can use below command

fldName.ShowInEditForm = false;

If you want to hide this field in display form, you can use below command

fldName.ShowInDisplayForm = false;

If you want to hide this field in list settings, you can use below command

fldName.ShowInListSettings = false;

If it is not a required filed then you can hide the item using Jquery in client side.

<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$('nobr:contains("Name")').closest('tr').hide();
});
// ]]></script>

No comments:

Post a Comment