Ad

Hide/Remove ContentType From A SP List With JavaScript

I am creating a SP List via REST API, and after the list has been created I'm adding a custom ContentType to that list. So, my custom ContentType should be a default CT on that List.

I've already tried this but it doesn't work, probably my contentType has to be an object..

let dfd = new $.Deferred();
let targetUrl = config.App + subsiteTitle;
let clientContext = new SP.ClientContext(targetUrl);

if (clientContext !== undefined && clientContext !== null) {
  let web = clientContext.get_web();
  let listCollection = web.get_lists();
  let list = listCollection.getByTitle(listTitle);
  let contentType = list.get_contentTypes().getById('0x01');
  contentType.deleteObject();

  clientContext.executeQueryAsync(
    Function.createDelegate(this, function() {
      dfd.resolve(this);
    }),
    Function.createDelegate(this, function(sender, args) {
      console.log('Failed to remove content type ' + args.get_message());
    })
  )
}

return dfd.promise();

Does anyone know how to hide or remove 'Item' ContentType from that List with JavaScript, or to set my custom ContentType as default, doesn't matter if it is via REST API or JSOM? Thanks a lot!

Ad

Answer

In your example two actions are missing:

Example

let ctx = new SP.ClientContext(targetUrl);

let ct = ctx.get_site().get_rootWeb().get_contentTypes().getById(contentTypeId);
let targetList = ctx.get_web().get_lists().getByTitle(listTitle);
let listContentTypes = targetList.get_contentTypes();
listContentTypes.addExistingContentType(ct); //1. add content type into list

var folder = targetList.get_rootFolder();
ctx.load(folder, 'ContentTypeOrder');
ctx.load(ct);
executeQuery(ctx)
    .then(() => {

        //2. set added content type as a default one   
        let ctIdList = folder.get_contentTypeOrder().sort((x,y) =>{ 
            return x.get_stringValue().indexOf(contentTypeId) != -1 ? -1 : y.get_stringValue().indexOf(contentTypeId) != -1 ? 1 : 0; 
        });
        folder.set_uniqueContentTypeOrder(ctIdList);
        folder.update();
        return executeQuery(ctx);
    })
    .then(() => {
        console.log("Done!");
    })

where

function executeQuery(context) {
    return new Promise((resolve, reject) => {
        context.executeQueryAsync(function () {
            resolve();
        }, function (sender, args) {
            reject(args);
        });
    });
}
Ad
source: stackoverflow.com
Ad