How to programmatically create a site column and a content type

Hello,
I'd like to create a site column (let's say a field text) and a content type, only  using c#  -i.e. I don't want to add new item/column and then xml. This code will be added to a FeatureActivated.My code is :
public override void FeatureActivated(SPFeatureReceiverProperties properties) {SPWeb rootweb = (SPWeb) properties.Feature.Parent;
SPFieldText field = new SPFieldText(SPfiledscollection???, "field1");
if (field != null)
rootweb.Fields.Add(field)
rootweb.Update();
}   SPContentType newContentType = new SPContentType(spcntenttypeId??, SPContentTypeCollection ??, "content1");
   rootweb.ContentTypes.Add(newContentType);
   rootweb.Update();
Are there any sample codes out there? I've only found samples using xml - which has an irritating "feature"
Thank you
Christos

Nice code and it helped me understand. Some small questions. I'm trying to make all the "data" for a (sub)web site.
So, I think, my steps are:
1. create site columns+content type
2. create  list
3. create a lookup site column that uses the list on <2>
4. create content type that uses the site column on <3>
5. Create the list for the content type on <4>
My confusion is: should I use one feature for everything? Your code is using scope=site, so i need to "hardcode" the web site's name. I don't mind doing that , I just don't know how to use scopes in features for creating data.
Thank you
Christos

Similar Messages

  • How can I update a Site Column with the content of an array with javascript CSOM?

    I'm relative new to Sharepoint 2013, I'm trying to update the content of a Site column with the content of an array, I can retrieve and visualize the content of my site column, the user is able to change and save the necessary part and the changes are
    saved into an array, now I have to update the content of the site column with the content of the array, but for some kind of reasons I can't accomplish that, any suggestion/example? This is my code so far to retrieve, visualize the site column and store the
    mofication into my array.
        <body>
                <select id="dropdown" name="dropdown" onchange="optSelect()">
                    <option value="EngineType_Cylinders">EngineType_Cylinders</option>
                    <option value="EngineType_EngineCycle">EngineType_EngineCycle</option>
                    <option value="EngineType_EngineFamily">EngineType_EngineFamily</option>
                    <option value="EngineType_Euro">EngineType_Euro</option>
                    <option value="EngineType_FamilyEvolution">EngineType_FamilyEvolution</option>
                    <option value="EngineType_GasEmissionLevel">EngineType_GasEmissionLevel</option>
                    <option value="EngineType_Power">EngineType_Power</option>
                    <option value="EngineType_PowerSupply">EngineType_PowerSupply</option>
                    <option value="EngineType_Use">EngineType_Use</option>
                </select><br />
                <textarea id="textareadisplay" rows="25" cols="23"></textarea><br />
                <input type ="button" value="Update values" onclick="addItemsToColumns()" />
            </body>
    My Javascript
        $(function () {
            SP.SOD.executeOrDelayUntilScriptLoaded(Function.createDelegate(this, function () {
               var select = document.getElementById('dropdown').value;
                console.log(select);
                getSiteColumns(select);
            }), 'SP.js');
        var fieldChoice;
        var choices;
        var addFields = [];
        var slc;
        var clientContext;
        function optSelect() {
            slc = document.getElementById('dropdown').value;
            getSiteColumns(slc);
        function getSiteColumns(selection) {
           clientContext = SP.ClientContext.get_current();
            if (clientContext != undefined && clientContext != null) {
                var web = clientContext.get_web();
                fieldChoice = clientContext.castTo(web.get_availableFields().getByTitle(selection), SP.FieldChoice);
                clientContext.load(this.fieldChoice);
                clientContext.executeQueryAsync(Function.createDelegate(this, this.OnLoadSuccess), Function.createDelegate(this, this.OnLoadFailed));
        function OnLoadSuccess(sender, args) {
            choices = fieldChoice.get_choices();
            var textarea = document.getElementById("textareadisplay");
            textarea.value = choices.join("\n");
        function OnLoadFailed(sender, args) {
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        function addItemsToColumns() {
            clientC = SP.ClientContext.get_current();
            var arrayForUpdate = $('#textareadisplay').val().split('\n');
            fieldChoice.set_item(, arrayForUpdate);
            fieldChoice.update();
            clientContext.executeQueryAsync(function () { }, function () { });
        function OnUpdateSuccess(sender, args) {
            var newchoices = fieldChoice.get_choices();
    My problem is on the function addItemsToColumns() please help! Thanks in advance.

    Let's look at your stylesheet -
    <style type="text/css">
    body {
    background-image: url(assets/images/Business%20Men%20In%20Reception%20Col.2.jpg);
    background-repeat: no-repeat;
    background-color: #003;
    margin-left:auto;
    margin-right:auto;
    position: relative;
    width: 960px;
    It's a good idea not to use spaces or any punctuation in your filenames when working for the web.
    #header {
    margin-left:auto;
    margin-right:auto;
    position: relative;
    width: 960px;
    #heading {
    font-family: Georgia, "Times New Roman", Times, serif;
    font-size: 36px;
    font-style: italic;
    font-variant: normal;
    margin-left:auto;
    margin-right:auto;
    There's no need to specify the default values (font-variant:normal) or to specify auto margins for any block element without an explicitly defined width. And wouldn't it make more sense to put the font style on the body tag, where it will inherit into the rest of the page than to restate it as you have done in the next rule?
    #bodytext {
    font-family: Georgia, "Times New Roman", Times, serif;
    font-size: 18px;
    line-height: 25px;
    font-variant: normal;
    width: 300px;
    #container {
    width: 960px;
    position: relative;
    margin-left:auto;
    margin-right:auto;
    .rightimg {
    float: right;
    margin-left: auto;
    padding-right: 40px;
    #heading #navbar ul li {
    padding: 30px;
    </style>
    Margin-left:auto can't work without knowing what the width of the element is....  Keep your CSS lean and targeted - it will help you to debug your layouts.

  • Adding multiple instances of a site column to a content type

    I read the posts at the link below (which references the exact same question that I will now ask), but is there any way to include multiple instances of the same site column (SC) to a content type (CT)?  The recommendation in the referenced thread is to create a copy of the SC for each column in the corresponding CT.  However, what I am attempting to do is create a document library, which contains a source document with an associated language, and a target document with an associated language.  Either, I need to create a list with both a source and target document that each store their own language, OR I need to add two columns, source language and target language, that are copies of the language column, OR I need a way to add the two aforementioned columns the way that I SHOULD be able to, which is by adding the language column twice, then changing the name accordingly.  Can anyone suggest the best way for me to do this?  Thanks,
    -Jeff
    The referenced thread:
    http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1864059&SiteID=1

    I have the same issue.  I have a list which I need to add two instances of the same site column: Originating Department and Routed Department.  They both need to use the Department site column but I am not allowed to add the site column twice
    in the same list.  Any help would be greatly appreciated.

  • Create Site Column and add it to two different list as dependent lookup column

    I want to create two lookup lists that will have one common column. The common column values will vary depending on the list.
    For ex: List A holds Countries (USA) and their Currency code (USD). List B holds States (New York) and their code (NY). The lists are completely independent of each other. I would like to create a common site column named "Code" of type
    Text and use it across these two lists. Is it possible?
    My solution so far -
    a. created the site column (programmatically) which is pretty straight forward.
    b. created list definition with two fields (Title and Code).
    c. created list instance for Country list. Added data rows in the elements.xml. But not sure how to add Code field as dependent lookup.
    If I remove the code field from the elements.xml, the solution deploys successfully creating the Country list with just the Title field. But I need both the fields. Any help is appreciated.
    Here is a look at the elements.xml with data rows for Country list instance
    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <ListInstance Title="List Instance" OnQuickLaunch="TRUE" TemplateType="10001" Url="Lists/CountryList" Description="Country Values">
    <Data>
    <Rows>
    <Row>
    <Field Name="Title">USA</Field>
    <Field Name="Code">USD</Field>
    </Row>
    <Row>
    <Field Name="Title">Japan</Field>
    <Field Name="Code">Yen</Field>
    </Row>
    <Row>
    <Field Name="Title">Australia</Field>
    <Field Name="Code">AUD</Field>
    </Row>
    </Rows>
    </Data>
    </ListInstance>
    </Elements>

    Hi,
    According to your post, my understanding is that you want to add lookup field to the list in elements.xml.
    I recoment you to create lookup column as site column, then bind the lookup column to the contnet type, and then use the contnet type in the list.
    For more information, you can refer to:
    http://spcodes.blogspot.com/2013/02/create-custom-content-type-with-lookup.html
    http://social.msdn.microsoft.com/Forums/office/en-US/d5ec08d5-cfa7-4bbb-9459-78d04674ee59/add-a-lookup-column-in-the-schemaxml?forum=sharepointcustomizationlegacy
    http://www.justanothertechnologyguy.com/2013/01/how-to-create-and-connect-lookup-fields.html
    Best Regards,
    Linda Li
    Linda Li
    TechNet Community Support

  • How to create a site column through Visual Studio 2010?

    I was trying to create lists, content type and site columns through Visual Studio 2010. But I could not figure out how to add site column? What item do I need to add for this and what kind of coding is to be done?

    Try this
    1. Create a Empty project in Visual studio.
    2.The Empty SharePoint Project template does not include any Features in the Features folder. To add a new Feature to this project, right -click the Features folder, and click Add Feature. This adds a new Feature component to the folder; double – click the
    Feature1 icon in Solution Explorer to modify the Feature ’ s
    metadata using the Feature designer. The Title and Description values appear on the Features pages in Site settings. It is a good idea to make these values
    descriptive so that administrators will know what they are adding to the site when they activate the feature.
    The feature ’ s scope determines where the feature can be activated within SharePoint. Please Note – Certain components, such as site columns, content types, Master pages, and Page Layouts, are installed at the site collection level and made available to all
    sites within the collection. These components require that the scope for the feature be set to “ Site. ”
    3. Next, add a new item to the project (Right – click project name ➪ Add ➪ New Item) and select the Empty Element template from the Add New Item dialog box.
    The Empty Element template is an XML fi le where you can enter CAML Field definitions.
    Following is what you will add in your elements.xml file –
    < Elements xmlns="http://schemas.microsoft.com/sharepoint/" >
    < Field ID="{76C140E1-D827-433B-AD38-257F9594B846}"
    Name="CustomCol"
    DisplayName="My Custom Site Column"
    Group="Custom group"
    Type="Text"
    Required="FALSE"/ >
    < Field ID="{5F516D92-969C-4661-81B9-C9210E2A2FDC}"
    Name="Choice Type"
    DisplayName="My Choice Type"
    Group="Custom group"
    Type="Choice"
    Required="FALSE" >
    < CHOICES >
    < CHOICE > Medical < /CHOICE >
    < CHOICE > Dental < /CHOICE >
    < CHOICE > Vision < /CHOICE >
    < CHOICE > Insurance < /CHOICE >
    < /CHOICES >
    < /Field >
    < /Elements >
    4. To deploy the Site Columns defined in the Elements file, right – click the project name in the Visual Studio Solution Explorer, and select Deploy. This will deploy the solution file to the solution store and activate the Feature in the targeted site collection.

  • How to set RelationshipDeleteBehavior on a list using a site column and content type programatically CSOM c#

    On Prem development machine, I'm writng a deployment routine in c# using the client object model.  I've created some site columns of type Lookup, I've created a content type and added those lookup columns to it and I've created a list using the
    content type.  I want to set the RelationshipDeleteBehavior property on some of the lookup columns in the list.  I'm also using the 16 assemblies.
    List list = cc.Web.GetListByTitle("MyList");
    cc.Load(list);
    cc.ExecuteQuery();
    Field f = list.Fields.GetByInternalNameOrTitle("MyLookupField");
    cc.Load(f);
    cc.ExecuteQuery();
    (f
    as
    FieldLookup).RelationshipDeleteBehavior =
    RelationshipDeleteBehaviorType.Restrict;
    f is returning as a Field but (f
    as
    FieldLookup) is returning null here.  Any insight on this?
    Thank you.
    Dan Budimir

    Hi,
    We can use SP.ClientContext.castTo method to convert the field to lookup field . The following code snippet for your reference:
    ClientContext context = new ClientContext("http://siteurl");
    NetworkCredential credentials = new NetworkCredential("username", "password", "domain");
    context.Credentials = credentials;
    Web web = context.Web;
    List list = web.Lists.GetByTitle("MyList");
    Field field = list.Fields.GetByInternalNameOrTitle("MyLookupField");
    FieldLookup lookupField = context.CastTo<FieldLookup>(field);
    lookupField.RelationshipDeleteBehavior = RelationshipDeleteBehaviorType.Restrict;
    lookupField.Indexed = true;
    lookupField.Update();
    context.ExecuteQuery();
    Thanks,
    Dennis Guo
    TechNet Community Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Dennis Guo
    TechNet Community Support

  • HT1386 How do I create one Apple ID and iTunes user name and password for all of my Apple products: iPad, iPhone, and iPod plus iTunes on my PC?

    How do I create one Apple ID and iTunes user name and password for all of my Apple products: iPad, iPhone, and iPod plus iTunes on my PC?

    Yes, I do have multiple devices and it appeared to me that every time I tried to sync or log onto iTunes, the password was incorrect.  Consequently, I was and am constantly changing it.  Wouldn't it be nice if Apple would simply say that you only need one Apple ID and one password regardless of the number of Apple devices you intend to sync via iTunes. 
    Barring the above, how about a way to merge all of the Apple IDs and passwords into one.

  • How do I create a new account and get stuff from the old account to the new account

    How do I create a new account and get stuff from the old account to the new account

    There are instructions on this page for creating a new account : Set up an Apple ID in iTunes
    Or if you don't want to give credit card details : Create an iTunes Store, App Store, or iBooks Store account without a credit card or other payment method
    But you won't be able to transfer purchases from your old account to it, all content that you download from the store will remain tied to the account that downloaded it.

  • How to get the current selected column and row

    Hi,
    A difficult one, how do i know which column (and row would also be nice) of a JTable is selected?
    e.g.
    I have a JButton which is called "Edit" when i select a cell in the JTable and click the button "Edit" a new window must be visible as a form where the user can edit the a part of a row.
    Then the column which was selected in the JTable must be given (so i need to know current column) and then i want the TextField (the one needed to be edited) be active with requestFocus(). So it would be
    pricetextfield.requestFocus();
    Problem now is that i have to click every time in the window the JTextField which was selected in the JTable. I have chosen for this way of editing because my application is multi-user and it would be too difficult for me when everybody did editing directly (catch signals, reload data, etc.).
    My question is how do I know the current column and the current row in a JTable?

    I'm not sure what your mean by the "current" row or column, but the following utility methods return
    which row and column have focus within the JTable.
    public static int getFocusRow(JTable table) {
        return table.getSelectionModel().getLeadSelectionIndex();
    public static int getFocusColumn(JTable table) {
        return table.getColumnModel().getSelectionModel().getLeadSelectionIndex();
    }

  • How do I create Equal Height Columns with my Background Images?

    Hi there,
    here is my page http://www.allthingsprintuk.co.uk/ATPHome.html
    My problem is that the side bar HTML list is coming off the page in IE. & also the html  in the header can look awful due to browser settings.
    My question is how do I create Equal Height Columns with my Background Images so that they fit with the HTML text? Is there a good link you can point me to, or a tutorial?
    The only way I can see by doing it is slicing my images up into 3 (top middle & bottom) & then setting the middle to repeat y????
    Or does anyone know of a way to create rounded corners WITH drop shadows in CSS that will work on all browsers?
    Thanks in advance
    Louisa

    Try these http://www.pixelan.com/

  • Each time I create a new album in IPhoto, photos from another album or from photo stream are automatically dumped into the new album..  how do I create a blank album and then import photos from a flash drive into the new album?

    each time I create a new album in IPhoto, photos from another album or from photo stream are automatically dumped into the new album..  how do I create a blank album and then import photos from a flash drive into the new album?

    just import the iPhoto
    Surely you meant "just import the photo"?  The Spell checker is dangerously creative !

  • How do I delete duplicate Site Columns in Sharepoint 2013

    When I got to save a site as a template I'm told that there are duplicate site columns and the template can not be saved.
    I found that under all of the e-mail submission site columns they are duplicated site columns  for example
     BCC
    Multiple lines of text
    Property Management
     BCC
    Multiple lines of text
    PMRG Connections
    I want to remove the Property Management   ( I know that this is the site  name where I copied it from), but they are duplicated all across the site collections.. every site  and site collection has it duplicated, is this because I
    enabled  lists to allow email submissions?
    either way I need to get rid of the duplicate  item, so I can save sites as templates if needed.

    There are a few required columns that can’t be deleted. They cannot be deleted through UI because
    the Delete button is not available (as you already mentioned in your previous post). The only available option is using C# code (SP object) or Powershell commends.
    By the way, I cannot find Date Received column in my Dev, I guess Date Received is the one of the columns added by custom feature. You may refer the link below for useful Powershell commend. It was written for SharePoint 2010 but should work in
    SharePoint 2013 as well.
    http://get-spscripts.com/2010/10/cant-remove-site-column-from-content.html
    백상하 - Stop hacking my blog http://blog.naver.com/agilepoint
    쉐어포인트 배움터 http://sharepointkorea.com

  • OK now that there is no option to reveal "database" panel in DW CC, how do I create a database connection and build my phpmysql pages?

    Is there an alternative way other than manually entering PHP code?

    Thanks, It works. Author of the article politely says what many of us have to say to Adobe when they make "improvements" - WTF, Adobe???
          From: Ben Pleysier <[email protected]>
    To: Jon Lane <[email protected]>
    Sent: Saturday, January 31, 2015 1:44 AM
    Subject:  OK now that there is no option to reveal "database" panel in DW CC, how do I create a database connection and build my phpmysql pages?
    OK now that there is no option to reveal "database" panel in DW CC, how do I create a database connection and build my phpmysql pages?
    created by Ben Pleysier in Dreamweaver support forum - View the full discussionWeb development tutorial
    Deprecated Server Behaviors for Dreamweaver Creative Cloud
    WebAssist A better, more secure and future proof way MySQLi Server Behaviors
    Dreamweaver extension
    WebAssist If the reply above answers your question, please take a moment to mark this answer as correct by visiting: https://forums.adobe.com/message/7148099#7148099 and clicking ‘Correct’ below the answer Replies to this message go to everyone subscribed to this thread, not directly to the person who posted the message. To post a reply, either reply to this email or visit the message page: Please note that the Adobe Forums do not accept email attachments. If you want to embed an image in your message please visit the thread in the forum and click the camera icon: https://forums.adobe.com/message/7148099#7148099 To unsubscribe from this thread, please visit the message page at , click "Following" at the top right, & "Stop Following"  Start a new discussion in Dreamweaver support forum by email or at Adobe Community For more information about maintaining your forum email notifications please go to https://forums.adobe.com/thread/1516624.

  • How do I create groups in Mail and add contacts to that group?

    How do I create groups in Mail and then add contacts to that group?

    Look in Mail > Preferences > Composing tab > If you want all the email addresses to show, check "When sending to a group, show all member addresses".   If unchecked, just the groupname should appear.
    If it still doesn't work then review the email addresses for each of the group members looking for errors in format.
    Also, clean up the list in previous recipients in Mail > Window > Previous Recipients.

  • How do you create a podcast playlist and get all unplayed podcasts copied to it?

    How do you create a podcast playlist and get all unplayed podcasts copied to it?

    Creat a Smart Playlist in iTunes (File -> New Smart Playlist) that looks like the following:
    Once you have successfully done that you can set it up to sync to your iPod Shuffle from under the Shuffle's Podcast configuration tab/pane in iTunes.
    B-rock
    B-rock

Maybe you are looking for

  • Custom security provider exception

    Good day, colleagues. I want to raise an old topic. I use custom security provider exceptions: -AccountExpiredException -AccountLockedException However, the login() method only captures FailedLoginException try   CallbackHandler pwcall = new weblogic

  • QM:Maximum skip duration in dynamic modification rule

    Hi Can anybody explain how the system behaves with    QM:Maximum skip duration in dynamic modification rule. Gobinathan G

  • [Solved] Harddisks: lot of output in both dmesg and kernel.log

    Situation: Since a few weeks I'm having a new little home server. An intel atom d525 cpu with 2gb ram, which seems to be a nice compromise between speed, price and power consumption. I'm wanting to use this server mainly as file server (backup, bulk

  • DELETING THE MASTER RECORDS

    Hi gurus, i want to upload the new master records into my system regarding the MM. first thing i want to delete the old records in the system and freshly want to load into the system. please give me the soluion how to do it. it is a development serve

  • 10.6 Slow - Adress Book fixed with smart group deletion

    10.6 was S...L....O.....W for me. still may be, but likely connected to this issue which i have solved. address book would take FOREVER to open. Any change would take FOREVER to log and allow to use again. activity monitor showed 100% CPU usage while