SharePoint 2013:如何使用JavaScript CSOM更新多值查找字段

SharePoint 2013: How to update multi-value lookup field using JavaScript CSOM

本文关键字:更新 查找 字段 CSOM JavaScript 2013 何使用 SharePoint      更新时间:2023-09-26

我有一个联系人列表,其中有一个名为ContactType的多值查找字段。CAML查询的结果将显示其中一个列表项的ContactType的以下值:

1;#Applicant;#2;#Employee

在对多值查找字段执行CSOM查询后,我看了看Fiddler,并注意到SP.FieldLookupValue对象有两个值属性:

$1E_1 : 1
$2e_1 : "Applicant"

然而,当您保存一个值时,您只能设置lookupId,在本例中为1。没有像lookup.set_lookupValue()那样设置值的方法。

我正在尝试将ContactType的内容复制到Contacts的新列表项中。不幸的是,我在更新ContactType字段时没有成功。这是我到目前为止所尝试的:

var clientContext = new SP.ClientContext.get_current(); 
var oList = clientContext.get_web().get_lists().getByTitle('Contacts');
var itemCreateInfo = new SP.ListItemCreationInformation();
var oListItem = oList.addItem(itemCreateInfo);
var contactTypes = new Array();
$.each(contact.contactTypes, function (index, contactType) {
    var lookup = new SP.FieldLookupValue();
    lookup.set_lookupId(contactType.id);
    contactTypes.push(lookup);
});
// other set_item statements skipped for brevity
oListItem.set_item('ContactType', contactTypes);
oListItem.update();

错误信息是:

Invalid lookup value. A lookup field contains invalid data.

我还尝试了下面的代码,但没有成功:

lookup.set_lookupId(contactType.id + ";#" + contactType.title);

在这种情况下,错误信息是:

The input string is not in the correct format.

如果我更新单个查找,我没有问题,但问题在于查找数组的保存。例如,下面的代码可以正常工作:

var lookup = new SP.FieldLookupValue();
lookup.set_lookupId(1);
contactTypes.push(lookup);
oListItem.set_item('ContactType', lookup);

,但当试图保存查找数组时,它不会像

那样发挥作用。
oListItem.set_item('ContactType', contactTypes);

任何想法?

不要构建SP.FieldLookupValue数组,而是将多个联系人类型保存为字符串。

var clientContext = new SP.ClientContext.get_current(); //if the page and the list are in same site.If list is in different site then use relative url instead of get_current
var oList = clientContext.get_web().get_lists().getByTitle('Contacts');
var itemCreateInfo = new SP.ListItemCreationInformation();
var oListItem = oList.addItem(itemCreateInfo);
var contactTypes = null;
$.each(contact.contactTypes, function (index, contactType) {
    if (index != 0)
        contactTypes += ';#' + contactType.id + ';#' + contactType.title;
    else
        contactTypes =  contactType.id + ';#' + contactType.title;
});
// other set_item statements omitted for brevity
oListItem.set_item('ContactType', contactTypes);
oListItem.update();
clientContext.executeQueryAsync(
    // success return
    function () {
        var success = true;
    },
    // failure return
    function (sender, args) {
        window.alert('Request to create contact failed. ' + args.get_message() +
                ''n' + args.get_stackTrace());
    })