0

I have a requirement to read a csv file and insert tasks into database. Trying with Apex because we need to associate them to Contacts but we don't have Contact Id instead we have Contact Email and other details. So need to search Contact for each row and associate a task to it. I am still in the beginning so trying to insert Tasks by populating all mandatory fields in the file. But getting an error called 'Invalid Id' while setting WhoId(Contact Id) on a task. If I remove that line, it's inserting fine. Am not sure if I am missing a key thing here or if we can't associate task to a Contact pro-grammatically. (the line in Bold is causing error)

public class importDataFromCSVController {
public Blob csvFileBody{get;set;}
public string csvAsString{get;set;}
public String[] csvFileLines{get;set;}
public List<Task> Tasklist{get;set;}
  public importDataFromCSVController(){
    csvFileLines = new String[]{};
    Tasklist = New List<Task>(); 
  }

  public void importCSVFile(){
       try{
           csvAsString = csvFileBody.toString();
           csvFileLines = csvAsString.split('\n'); 

           for(Integer i=1;i<csvFileLines.size();i++)
           {
               Task taskObj = new Task();
               string[] csvRecordData = csvFileLines[i].split(',');
               taskObj.OwnerId = csvRecordData[0];
               taskObj.Subject = csvRecordData[1];
               taskObj.Status = csvRecordData[2];
               taskObj.Priority = csvRecordData[3];
               taskObj.WhatId = csvRecordData[4];
              **taskObj.WhoId = csvRecordData[5];**
               Tasklist.add(taskObj);   
           }
           Insert Tasklist;
        }
        catch (Exception e)
        {
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured while importin data Please make sure input csv file is correct');
            ApexPages.addMessage(errorMessage);
        }  
  }
}

Error in Debug Log:: |VARIABLE_SCOPE_BEGIN|[31]|e|Exception|true|false 16:43:43.0 (17110101) |VARIABLE_ASSIGNMENT|[31]|e|"common.apex.runtime.impl.ExecutionException: Invalid id: 003g000001VvWkR\r"|0x6add22b6 16:43:43.0 (17117180) |STATEMENT_EXECUTE|[31]

2 Answers 2

1

There was some trailing white space in your data which was causing the code to fail, because Id fields can't contain any white space. As such, you should trim any white space from the value if it is not null.

if(String.isNotEmpty(csvRecordData[5])) {
    taskObj.WhoId = csvRecordData[5].trim()
}
1

So the WhatID on a task record must be a record ID of an object that has "Allow Activities" checked.

What I would do is use a map of email address => record ID for your existing contacts.

Map<String, ID> emailAddressToContactID = new Map<String,ID>();
for(Contact c: [SELECT ID, Email FROM Contact WHERE Email != null]){
   emailAddressToContactID.put(c.Email, c.Id);
}

Then use the map in the line which is failing.

taskObj.WhatId = emailAddressToContactID.get(csvRecordData[4]);

This may fail if you have a whole lot of contacts, but if your data-set is small, it should do the trick!

10
  • 1
    This will still fail, it's WhoId for a Contact or Lead, not WhatId.
    – sfdcfox
    Commented Dec 1, 2017 at 21:30
  • I am sorry it's my bad. I missed the line that's causing issue. Yes it's erroring while setting 'WhoId'. An in my file I have used Id of Contact, still it says Invalid Id. And when I used the same csv file via Data Loader, it inserted successfully.!!
    – Amulya
    Commented Dec 1, 2017 at 21:32
  • 1
    @Amulya In Apex Code, you have to "translate" the email yourself, while the Data Loader can use an API to match by email (as well as, say, the Import Wizard).
    – sfdcfox
    Commented Dec 1, 2017 at 21:34
  • Actually I haven't gone till there yet. As per my plan, I will write a logic to search Contact based on Email+Account Id+Contact Names combination. For now i am just verifying if I can insert task programatically. To be clear, below is the content of my file. Owner-----Subject----Status---Priority---Opportunity---Contact ====> 005g0000003Qren---Call---Draft---3-Medium---006g000000COc8N---003g000001VvWkR
    – Amulya
    Commented Dec 1, 2017 at 21:36
  • 1
    @Amulya I suspect a typo in your data. If you're getting an invalid Id error exactly at that line, that means that the system is implicitly converting the String to an Id and failing. Make sure the string is exactly 15 or 18 characters long, that there are no extra quotes, spaces, or anything else on the value. It must be exactly the right length. Try: csvRecordData[5].trim(). I actually suspect there's a \r lurking in there.
    – sfdcfox
    Commented Dec 1, 2017 at 21:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .