2

Has anyone tried with creating some 20+ Single line of text SPField using Client Side OM, like within a Content Editor Web Part.
Because creating a SPList with these many number of columns using SharePoint UI is a tedious job, which is meant for testing purposes only.
I am looking for some kind of code that's doing this, available already.

0
6

Since you want to put this into a content editor you'll need to use the JavaScript Client Object Model. Here is something you can use as the source for a content editor that will ask you the list and field title, then let you click a button to create the field, adjust/expand on it as necessary:

<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.js""></script>
<label for="in_listName">List to create field in:</label>
<input id="in_listName"></input>
<label for="in_fieldName">Enter a name for your new field:</label>
<input id="in_fieldName"></input>
<button id="btn_createField" type="button">Create Field</button>

<script>
    function createColumns_click(listTitle, fieldTitle) {
        var myCtx = SP.ClientContext.get_current();
        var myList = myCtx.get_web().get_lists().getByTitle(listTitle);
        var newField = myList.get_fields().addFieldAsXml("<Field DisplayName=\'" + fieldTitle + "\' Type=\'Text\' />", true, SP.AddFieldOptions.defaultValue);
        newField.update();
        myCtx.executeQueryAsync(function(){
            alert("Field <" + fieldTitle + "> created!");
        }, function(sender, args){
            alert("Error:\n" + args.get_message());
        });
    }

    $(function() {
        $("#btn_createField").click(function() {
            var listName = $("#in_listName").val();
            var fieldName = $("#in_fieldName").val();
            createColumns_click(listName, fieldName);
        });
    });
</script>

If you're already using jQuery you can omit the script tag at the top.

I don't actually like using the fields.addFieldAsXml function, I wish it was easier to create an SP.FieldText (or any other type) object, but trying to create the object directly on the list like other ClientObjects gives me a constructor error; I haven't found any good examples on how to create new SP.FieldText objects directly.


Edit:

Here is how you could use a semi-colon seperated list as one of the inputs so that you could create multiple fields at the same time:

<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.js""></script>
<div>
    <label for="in_listName">List to create field in:</label>
    <input id="in_listName"></input>
</div>
<div>
    <label for="in_fieldName">Enter a semi-colon seperated list of field titles:</label>
    <input id="in_fieldName"></input>
</div>
<button id="btn_createField" type="button">Create Field</button>

<script>    
function createColumnsArr_click(listTitle, fieldTitles) {
    var myCtx = SP.ClientContext.get_current();
    var myList = myCtx.get_web().get_lists().getByTitle(listTitle);
    $.each(fieldTitles, function (idx, item) {
        var newField = myList.get_fields()
            .addFieldAsXml(
            "<Field DisplayName=\'" + item + "\' Type=\'Text\' />",
            true,
            SP.AddFieldOptions.defaultValue
            );
        newField.update();
    });
    myCtx.executeQueryAsync(function () {
        alert("Created fields:/n" + fieldTitles.toString());
    }, function (sender, args) {
        alert("Error:\n" + args.get_message());
    });
}

$(function () {
    $("#btn_createField").click(function () {
        var listName = $("#in_listName").val();
        var fieldName = $("#in_fieldName").val().split(";");
        createColumnsArr_click(listName, fieldName);
    });
});
</script>
5
  • But he wants to do all this in one go and not one by one. This is similar to doing it the UI way.
    – Akhoy
    Oct 16 '15 at 15:44
  • @Akhoy It saves a number of clicks, scrolling, and form entry per field. Additionally, you could easily modify it to take an array of fieldTitles and loop through the new field creation section (var newField ...; newField.update();) before calling myCtx.executeQueryAsync. Plus it uses the client object model, and it can be used inside of a content editor, as specified in the OP's question.
    – John-M
    Oct 16 '15 at 15:52
  • 1
    Right. This is better than the previous answer then. Needs only 1 POST compared to 20+ POSTs. I think you should also include the array part since i think that is what the OP wants. +1
    – Akhoy
    Oct 16 '15 at 15:57
  • 1
    @akhoy - updated
    – John-M
    Oct 16 '15 at 16:15
  • This one is better that me. Should be accepted +1 Oct 16 '15 at 16:29
3

Did not try yet but know the trick using REST API. You have to send 20+ POST requests to the following URL

/_api/web/lists(guid'Guid Id of your list')/fields

Request body will be

var data = {
    '__metadata': {
        'type': 'SP.FieldText'
    },
    'FieldTypeKind': 2,
    'Title': 'Project Name',
    'MaxLength': '22'
};

Update based on comment. Write a function like following

    function addField(fieldName) {

    var data = {
        '__metadata': {
            'type': 'SP.FieldText'
        },
        'FieldTypeKind': 2,
        'Title': fieldName,
        'MaxLength': '22'
    }

    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('Your List Name')/Fields",
        type: "POST",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "content-Type": "application/json;odata=verbose"
        },
        data: JSON.stringify(data),
        success: function(data) {
            console.log(data);
        },
        error: function(error) {
            alert(JSON.stringify(error));
        }
    });
}

Now execute the function 20+ times by providing your fieldName parameter.

NB: Change the List name in url

But you should use PowerShell for creating multiple columns. See here

$List = $Context.Web.Lists.GetByTitle($ListTitle)
$Context.Load($List)
$Context.ExecuteQuery()

# Add new field to the list
$List.Fields.AddFieldAsXml("<Field Type='Text' DisplayName='Location'/>", $true, [Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$List.Update()
$Context.ExecuteQuery()
8
  • comment will be appreciated in case down vote Oct 16 '15 at 13:49
  • 1
    tip: Use Chrome Snippets to built a collection of snippets in your (SharePoint) Toolbelt. (ps. downvote was not me) Oct 16 '15 at 13:49
  • It's ok but I did not get the actual problem of my current code snippets Oct 16 '15 at 13:52
  • Am not aware of REST API.I need to look into this, how to use this.Thanks for the info and sample. Oct 16 '15 at 14:14
  • 1
    Am I making sense now @DannyEngelman boss? Oct 16 '15 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.