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

5

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

1;#Applicant;#2;#Employee

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

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

然而,当您保存值时,只能设置查找ID,本例中为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);

有什么想法吗?
1个回答

4
不要构建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());
    })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接