This SharePoint tutorial explains, how to create site column in SharePoint 2013/2016/Online.
- Create SharePoint Site Column programmatically
- Create SharePoint Site Column using PowerShell
- Create SharePoint Site Column using JavaScript
- Create SharePoint Site Column using Rest API
SharePoint Site Column
Site columns in SharePoint 2013/2016/Online are reusable fields that we can use across multiple, navigate to the Site Settings page lists within a site. So if you have created a site column in a site, then the site column will be available to use in the current site as well as the child sites in the site hierarchy.
So if you have created a site column in a top-level site in the site collection, then the site column will be available to use in the entire site collection.
Out of box, SharePoint has more than 400 site columns in the top level site, out of them many are also hidden. You can navigate to Site Column gallery from the site settings page to see the site columns.
The Site Column in SharePoint helps you by providing a reusable column within your site and subsites. Once you create a site column at our top-level site, we can use that site column in the subsites as well in SharePoint.
Create site column in SharePoint 2013/2016/Online
Now, we will see how to create site column in sharepoint 2013 or create site column in sharepoint online.
Follow the below step to create a site column in SharePoint 2013/2016/Online.
Ste-1: Open your SharePoint site -> Site settings
Step-2: Under Web Designer Galleries section -> Click on Site Columns
Step-3: Click on Create button to create a new site column.
Step-4: There are many out of box site column which is provided by Microsoft.
Step-5: Once you click on Create, you can redirect to next page for creating the columns in SharePoint. Please enter the column name and set the datatype.
Read SharePoint 2013 list item level permission using REST API
Create site column using JavaScript Object Model
We can use the JavaScript client object model to create a site column in SharePoint. You can create any web part page and then add a script editor web part on it. Then put the below code and Save the page.
<input type='button' value='Create Site Column' onclick="createSiteColumn();"/>
<script language="javascript" type="text/javascript">
function createSiteColumn() {
var xmlDef = "<Field DisplayName='WebSiteName' Type='Text'/>";
var ctx = new SP.ClientContext.get_current();
var field = ctx.get_web().get_fields().addFieldAsXml(xmlDef, false, SP.AddFieldOptions.addToNoContentType);
ctx.load(field);
field.set_group("EnjoySharePoint Site Columns");
field.updateAndPushChanges(false);
ctx.executeQueryAsync(success, failure)
}
var success = function () {
alert('Site column created successfully !!!');
}
var failure = function () {
alert('Error occured while creating site column.');
}
</script>
Click on the button, it will display a message saying “Site column created successfully !!!” if the site column was created successfully.
Now navigate to the Site Settings page, then click on “Site columns ” under Web Designer Galleries.
In the Site Columns page, search based on EnjoySharePoint Site Columns group, you will be able to see our site column name as: WebSiteName like below:
Create SharePoint site column using REST API
Below is the code to create a site column in SharePoint 2013 using Rest API. You can put the below code in a script editor web part or content editor web part in SharePoint 2013/2016 or SharePoint Online.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function(){
$("#btnClick").click(function(){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/fields";
$.ajax({
url: requestUri,
type: "POST",
data: JSON.stringify(
{ '__metadata': { 'type': 'SP.Field' },
'Title': 'Web Site Lists',
'FieldTypeKind': 2,
'Group': 'EnjoySharePoint Site Column'
}),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
alert('Site column created successfully');
}
function onError(error) {
alert(JSON.stringify(error));
}
});
});
</script>
<input type="button" id="btnClick" value="Create Site column using REST API"/>
Here FieldTypeKind determines which type the field type is. 2 means the type is Text. You can check out this article to know the value for different types.
Click on the button, it will display a message saying “Site column created successfully !!!” if the site column created successfully. It will be displayed like below:
Create SharePoint Site Column using PowerShell
Here we will discuss, how to create a site column using PowerShell in SharePoint 2013/2016.
Below is the PowerShell command to create a site column in SharePoint 2013/2016. You can run the below command in Windows PowerShell ISE.
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
$site = get-SPSite http://win-pfcp2dgt8di/sites/EnjoySharePoint/
$web = $site.RootWeb
$columnDisplayName="My WebSites Column From PowerShell"
$columnInternalName="scMyWebSitesFromPowerShell"
$sitecolumnFieldType="Choice"
$web.Fields.Add($columnInternalName,$sitecolumnFieldType,$false)
$spChoiceField=$web.Fields.GetField($columnInternalName)
$spChoiceField.Group="MyCustomSiteColumns"
$spChoiceField.Choices.Add("EnjoySharePoint.com")
$spChoiceField.Choices.Add("OnlySharePoint2013.com")
$spChoiceField.Choices.Add("Fewlines4biju.com")
$spChoiceField.Title=$columnDisplayName
$spChoiceField.DefaultValue="EnjoySharePoint.com"
$spChoiceField.FillInChoice=$true
$spChoiceField.Update()
$web.Dispose()
$site.Dispose()
Once the command runs successfully, it will create the site column which we can be able to see in the Site column page. It looks like below:
Read How to use SharePoint Alert Me feature in list or library
Create a SharePoint Site Column using Visual Studio
Follow the below steps to create a site column using Visual studio 2013/2015/2017 in SharePoint 2013/2016.
Open Visual Studio 2013/2015/2017 then File -> New -> Project. In the New Project dialog box, you will be able to see the lots of project templates. From the left side you can go to Installed -> Templates -> Visual C# -> Office/SharePoint -> SharePoint Solutions. Then in the right side choose SharePoint 2013 – Empty Project.
Then give a name for the project location where you want to Save and the name of the Solution and then click on OK. Here make sure you have selected .NET Framework version 4.5 is selected. Because .NET Framework 3.5 is not supported in SharePoint 2013.
In the next screen in SharePoint, Customization wizard gives a local SharePoint URL for debugging and then choose the option as Deploy as a sandboxed solution.
This will create a solution for us. Then right-click on the Project -> Add -> New Item… which will open the Add New Item dialog box. From the list of templates, choose the Site Column template as shown in the fig below:
Once you will add this you can see the Elements.xml file which looks like below:
<?xml version="1.0″ encoding="utf-8″?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Field
ID="{ce590f27-49bb-4fc5-900e-a34687d81c3f}"
Name="MySiteColumnFromVisualStudio"
DisplayName="My Site Column From Visual Studio"
Type="Text"
Required="FALSE"
Group="Custom Site Columns">
</Field>
</Elements>
Here, by default, it adds a site column with a Single line of text type. Here I have changed a few things like instead of a single line of text, I have changed to a Choice column (set Type=”Choice”). Then I have added 3 values to the Choice column. Then I have changed the Group name to my custom group name which looks like below:
<?xml version="1.0″ encoding="utf-8″?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Field
ID="{ce590f27-49bb-4fc5-900e-a34687d81c3f}"
Name="MySiteColumnFromVisualStudio"
DisplayName="My Site Column From Visual Studio"
Type="Choice"
Required="FALSE"
Group="MyCustomSiteColumnss">
<CHOICES >
<CHOICE>EnjoySharePoint.com</CHOICE>
<CHOICE>OnlySharePoint2013.com</CHOICE>
<CHOICE>Fewlines4Biju.com</CHOICE>
</CHOICES>
</Field>
</Elements>
The solution explorer looks like below:
I have not changed anything in the Features node. By default, it comes as Web scope.
Now we can right-click and Deploy the solution. Once the solution deployed successfully, you can go to the Site features page (Site Settings -> click on “Manage site features” which is under Site Actions section). You should be able to see our feature already activated, which means our site column should be created successfully.
Now go to Site Setting page, Then from Web Designer Galleries click on “Site columns“, there we should be able to see the site column. It looks like below:
Add Site Columns to SharePoint List
Step-1: Create or open your existing List in SharePoint -> Go to the List Settings
Step-2: Next, Click on Add from Existing Site Columns.
Step-3: Select Custom columns in the drop down list.
Step-4: Select your column and click Add
Step-5: Then Click on OK button and Once you click on OK, you will redirect to view page.
Read How to use _spPageContextInfo JavaScript variable in SharePoint
Add SharePoint site column to list programmatically using CSOM
Let us see, how to add site columns to existing SharePoint Online lists or document libraries using csom (.Net managed object model code).
Recently I got one requirement to add one site column to a few lists and document libraries using C#.Net (Microsoft.SharePoint.Client.dll) code.
Add site column to list programmatically using CSOM in SharePoint
Here I have created a console application and written the below method which will take a single parameter as URL (need to provide the site URL).
Here the listNames contains all my lists. As per my requirement, I have added the same site column to 3 different lists.
private static IList<string> listNames = new List<string>();
public static void AddSiteColumnToExistingList(string URL)
{
listNames.Add("List1");
listNames.Add("List2");
listNames.Add("List3");
using (ClientContext ctx = new ClientContext(URL))
{
ctx.AuthenticationMode = ClientAuthenticationMode.Default;
ctx.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
foreach (string targetListName in listNames)
{
List targetList = ctx.Web.Lists.GetByTitle(targetListName);
ctx.Load(targetList);
ctx.ExecuteQuery();
string siteCols = "MySiteColumnName";
FieldCollection fieldCollection = ctx.Web.AvailableFields;
ctx.Load(fieldCollection);
ctx.ExecuteQuery();
Field myField = Enumerable.FirstOrDefault(fieldCollection, ft => ft.InternalName == siteCols);
targetList.Fields.Add(myField);
targetList.Update();
ctx.ExecuteQuery();
}
}
}
private static SecureString GetSPOSecureStringPassword()
{
try
{
var secureString = new SecureString();
foreach (char c in "MyPassword")
{
secureString.AppendChar(c);
}
return secureString;
}
catch
{
throw;
}
}
private static string GetSPOAccountName()
{
try
{
return "bijay@<[email protected]>";
}
catch
{
throw;
}
}
Once you will run the code, it will add the “MySiteColumnName” site column to all the 3 SharePoint Online lists.
Add site column to content type programmatically using JavaScript in SharePoint
Below is the JavaScript code to add an existing site column to content type using JavaScript Object Model in SharePoint Online or SharePoint 2013/2016.
Just create a web part page, and then edit that web part page and add a script editor web part.
Insert the below JavaScript code to the script editor web part. Save the page.
<script language="javascript" type="text/javascript">
function AddContentType() {
var ctx = new SP.ClientContext.get_current();
var field = ctx.get_site().get_rootWeb().get_fields() .getByInternalNameOrTitle("Company_x0020_Branches");
var ctype = ctx.get_site().get_rootWeb().get_contentTypes() .getByI("0x0100BD927BBDD704954CB6FEA329CB809491″);
ctx.load(ctype);
ctx.load(field);
var createInfo = new SP.FieldLinkCreationInformation();
createInfo.set_field(field);
var fieldLink = ctype.get_fieldLinks().add(createInfo);
ctype.update (true);
ctx.load(fieldLink);
ctx.executeQueryAsync(success, failure);
}
function success() {
alert('success');
}
function failure() {
alert('failure');
}
</script>
<button type="button" onclick="AddContentType();">Add Site Column to Content Type</button>
Here you need to give the Site column’s internal name. And The GUID of the content type.
Click on the button, it will add the site column to the content type.
Now if you will open the content type, you will be able to see the site column added to the content type.
You may like the following SharePoint tutorials:
- How to Check SharePoint version installed on the server?
- Download SharePoint Manager
- Excel cannot connect to the SharePoint list
- Page Viewer Web Part in SharePoint
- SharePoint Find an Item List search box does not return results
- How to Change Layout of a Page in SharePoint 2013
- The workbook cannot be opened error in SharePoint 2013
I hope this SharePoint tutorial helps to learn how to create site column in SharePoint 2013/2016/Online. We also saw how we can add existing site columns to a SharePoint Online list.
- SharePoint Site Column
- Create site column in SharePoint 2013/2016/Online
- Create site column using JavaScript Object Model
- Create SharePoint site column using REST API
- Create SharePoint Site Column using PowerShell
- Create a SharePoint Site Column using Visual Studio
- Add Site Columns to SharePoint List
- Add SharePoint site column to list programmatically using CSOM
- Add site column to content type programmatically using JavaScript in SharePoint
Rajkiran is currently working as a SharePoint Consultant in India . Rajkiran having 7+ years of experience in Microsoft Technologies such as SharePoint 2019/2016/2013/2010, MOSS 2007,WSS 3.0, Migration, Asp.Net, C#.Net, Sql Server, Ajax, jQuery etc.He is C#Corner MVP (2 Times).
Hi there,
Not sure if you are still monitoring this article, but I have a question…
Can we add a single line text column across all sites and site collection?
Say, ColumnX is created and want to add to the base columns that I could add to any site or any site collection on the SharePoint tenant.
Please help/advise. (I was able to create the column at the top most site, but it is unavailable to add on other sites!!!)