使用RStudio更新salesforce记录 - 如何从数据框更新多个记录?

时间:2018-04-06 02:50:34

标签: r salesforce

我尝试使用Rforcecom更新Salesforce记录列表。

如果我使用此代码更新一条记录,它可以完美运行:

objectName <- "Opportunity"
id <- "0060W00000wzkmH" #actual record ID of one specific record in salesforce
fields <- c(PatronDonate__Acknowledged__c="true")
rforcecom.update(session, objectName, id, fields)

但是当我尝试遍历数据框以更新多个记录时,它会抛出此错误:

length(url) == 1 is not TRUE

我已经尝试了几种不同的方法来实现这一点而没有运气,如果我将特定的salesforce记录ID替换为我需要提供的数据帧标识符以便代码迭代,它们都可以工作。例如,这不起作用:

nrowsdf <- nrow(dataframe)
for(i in 1:nrowsdf) {  
  objectName <- "Opportunity"
  id <- dataframe$Record.ID
  fields <- c(PatronDonate__Acknowledged__c="true")
  rforcecom.update(session, objectName, id, fields)
}

但这确实有效(它会更新一条特定记录,但显然它不会更新记录列表):

nrowsdf <- nrow(dataframe)
for(i in 1:nrowsdf) {  
    objectName <- "Opportunity"
    id <- "0060W00000wzkmH"
    fields <- c(PatronDonate__Acknowledged__c="true")
    rforcecom.update(session, objectName, id, fields)
}

非常感谢任何帮助。我之前没有与Rforcecom或salesforce合作过。

2 个答案:

答案 0 :(得分:1)

我找到了一种方法,通过循环指定每次迭代的行来使其工作:

inc <- function(x)
{
  eval.parent(substitute(x <- x + 1))
}

setrow <- 0

upsert <- function(x) {
  nrowsdf <- nrow(Records)
  for(i in 1:nrowsdf) {  
    newrow <- inc(setrow)
    fields <- c(PatronDonate__Acknowledged__c="1")
    rforcecom.update(session, "Opportunity", dataframe$Record.ID[newrow], fields)
  }
}

答案 1 :(得分:0)

salesforcer包可以通过直接在data.frames上进行操作来使用REST,SOAP或Bulk API更新记录,因此不需要循环。这是一个示例:

library(tidyverse)
library(salesforcer)
sf_auth(username, password, security_token)

n <- 2
new_contacts <- tibble(FirstName = rep("Test", n),
                       LastName = paste0("Contact-Create-", 1:n))
created_records <- sf_create(new_contacts, "Contact")
created_records
#> # A tibble: 2 x 2
#>   id                 success
#>   <chr>              <lgl>  
#> 1 0033s00000zN3JvAAK TRUE   
#> 2 0033s00000zN3JwAAK TRUE

updated_contacts <- created_records %>%
    select(id) %>%
    mutate(FirstName = "TestTest")
updated_records <- sf_update(updated_contacts, "Contact")
updated_records
#> # A tibble: 2 x 2
#>   id                 success
#>   <chr>              <lgl>  
#> 1 0033s00000zN3JvAAK TRUE   
#> 2 0033s00000zN3JwAAK TRUE

# confirm update by querying the fields of these two records
my_soql <- sprintf("SELECT Id, 
                           FirstName, 
                           LastName
                   FROM Contact 
                   WHERE Id in ('%s')", 
                   paste0(created_records$id , collapse="','"))
queried_records <- sf_query(my_soql)
#> # A tibble: 2 x 3
#>   Id                 FirstName LastName        
#>   <chr>              <chr>     <chr>           
#> 1 0033s00000zN3JvAAK TestTest  Contact-Create-1
#> 2 0033s00000zN3JwAAK TestTest  Contact-Create-2