How do I run this JSOM
-
07-02-2021 - |
Domanda
I was looking for ways I can automatically change the content type of my files inside SharePoint online. I go a code from Here
I'm not sure how the code is supposed to work. Added a Webpart, scripteditor on my document library.
At the part in the code where is says contenttypeId, I've pasted the content type id I want the files to be change to.
Nothing is happening. Not sure how the code is supposed to work.
Here is the code:
var contenttypeId = '0x01040005B1FCA568800F4FB4162C7A09742E67';
var lisTitle = "TestNewList";
var listitemId = 1;
UpdateListItem(lisTitle, listitemId, contenttypeId);
function UpdateListItem(listTitle, listitemId, contenttypeId) {
var clientContext = new SP.ClientContext();
oList = clientContext.get_web().get_lists().getByTitle(listTitle);
oListItem = oList.getItemById(listitemId);
oListItem.set_item('ContentTypeId', contenttypeId);
oListItem.update();
clientContext.load(oListItem, 'Id', 'Title', 'ContentTypeId');
clientContext.executeQueryAsync(
Function.createDelegate(this, function() {
var listsInfo = '';
listsInfo += oListItem.get_item('Title') + '\t' + oListItem.get_item('ContentTypeId');
console.log(listsInfo.toString());
}),
Function.createDelegate(this, function(sender, args) {
console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
})
);
}
Soluzione
Before running the code snippet, need to enable the Content Type Management for the library and add the Content Type needed in library settings,for example, I want to set Content Type "Images" for Item 7 which is an image:
Also, make sure passed valid list name and item Id in the code snippet, this is my test snippet(item Id: 7, list name: doc2):
<script type="text/javascript" language="javascript">
ExecuteOrDelayUntilScriptLoaded(runCode, "sp.js");
function runCode(){
var contenttypeId = '0x0101009148F5A04DDD49CBA7127AADA5FB792B00AADE34325A8B49CDA8BB4DB53328F2140047E654AF66AF2C4699BC331533868D61';
var lisTitle = "doc2";
var listitemId = 7;
UpdateListItem(lisTitle, listitemId, contenttypeId);
}
function UpdateListItem(listTitle, listitemId, contenttypeId) {
var clientContext = new SP.ClientContext();
oList = clientContext.get_web().get_lists().getByTitle(listTitle);
oListItem = oList.getItemById(listitemId);
oListItem.set_item('ContentTypeId', contenttypeId);
oListItem.update();
clientContext.load(oListItem, 'Id', 'Title', 'ContentTypeId');
clientContext.executeQueryAsync(
Function.createDelegate(this, function() {
var listsInfo = '';
listsInfo += oListItem.get_item('Title') + '\n' + oListItem.get_item('ContentTypeId');
alert(listsInfo.toString());
}),
Function.createDelegate(this, function(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
})
);
}
</script>