javascriptsharepoint-onlinesharepoint-listsharepoint-jsom

How to change column type of SharePoint online list using JSOM?


I want to change the column type of list using JSOM. The type of column "Billable" is Boolean and I need to change the type of column to "Single line of text".

Is there any method to change the type of column?

Here is code:

var oFields, clientContext;
function UpdateListField() {
    // You can optionally specify the Site URL here to get the context
    // If you don't specify the URL, the method will get the context of the current site
    // var clientContext = new SP.ClientContext("http://MyServer/sites/SiteCollection");
    clientContext = new SP.ClientContext(appUrl);

    var web = LawApp.Repositories.getWeb(clientContext, hostUrl);

    var olistCollection = web.get_lists();

    var oList = olistCollection.getByTitle("ODMatter");

    oFields = oList.get_fields();

    clientContext.load(oFields);

    // Execute the query to the server.
    clientContext.executeQueryAsync(onsuccess, onfailed);
}

function onsuccess() {

    // Iterate through Enumerator
    var oEnumerator = oFields.getEnumerator();

    while (oEnumerator.moveNext()) {
        var oField = oEnumerator.get_current();

        // Enter the field name here
        if (oField.get_title() == "Billable") {
            oField.FieldType("text");
            oField.update();
            break;
        }
    }

    // Execute the query to the server.
    clientContext.executeQueryAsync(FinalQuerySuccess, FinalQueryFailure);

}

function onfailed(sender, args) {
    console.log('Failed' + args.get_message() + '\n' + args.get_stackTrace());
}

function FinalQuerySuccess(sender, args) {
    updateCurrentVersion();
    console.log('Success');
}

function FinalQueryFailure(sender, args) {
    console.log('Failed' + args.get_message() + '\n' + args.get_stackTrace());
}

Solution

  • You need to use SP.Field.set_typeAsString () method to change the column type, below is my sample:

    var list = web.get_lists().getByTitle("Mylist");
    field = list.get_fields().getByInternalNameOrTitle("Billable");   
    field.set_typeAsString("Text");
    field.update();
    

    Reference: https://learn.microsoft.com/en-us/previous-versions/office/sharepoint-visio/jj245910(v=office.15)