public class importDataFromCSVController {
public Blob csvFileBody{get;set;}
public string csvAsString{get;set;}
public String[] csvFileLines{get;set;}
public List<account> acclist{get;set;}
public map<string, string> csvmap = new map<string, string>();
public map<string, Account> accmap = new map<string, Account>();
List<Type__c> typeList = new List<Type__c>();
public importDataFromCSVController(){
csvFileLines = new String[]{};
acclist = New List<Account>();
}
public void importCSVFile(){
try{
csvAsString = csvFileBody.toString();
csvFileLines = csvAsString.split('\n');
for(Integer i=1;i<csvFileLines.size();i++){
string[] csvRecordData = csvFileLines[i].split(',');
if(csvmap.containsKey(csvRecordData[0])){
csvmap.put(csvRecordData[0],csvmap.get(csvRecordData[0])+','+csvRecordData[2]);
}
else{
csvmap.put(csvRecordData[0],csvRecordData[2]) ;
}
}
system.debug('@@@@@@'+ csvmap);
/* for(string str : csvmap.keyset())
{
Account accObj = new Account() ;
accObj.name = str ;
accObj.test__c= csvmap.get(str);
acclist.add(accObj);
}
insert acclist;*/
for(string str : csvmap.keyset())
{
Account accObj = new Account() ;
accObj.name = str ;
accObj.test__c= csvmap.get(str);
accmap.put(str , accObj);
}
insert accmap.values();
Map<Id, set<string>> typeAccMap = new Map<Id, set<string>>();
for(Integer i=1;i<csvFileLines.size();i++){
string[] csvRecordData = csvFileLines[i].split(',');
if(accmap.containsKey(csvRecordData[0])){
Account acc = accmap.get(csvRecordData[0]);
if(typeAccMap.containsKey(acc.id))
{
Set<String> typeSet = typeAccMap.get(acc.id);
if(! typeSet.contains(csvRecordData[3]))
system.debug('@@@@@' + typeSet);
system.debug('@@@@@' + csvRecordData[3]);
{
Type__c t = new Type__c (Name = csvRecordData[3], Account__c = acc.id);
typeList.add(t);
// **typeAccMaptypeAccMap.put(csvRecordData[0], typeAccMap.get(csvRecordData[0]).add(csvRecordData[3]));**///error;
Set<string> istmpSet happening= heretypeAccMap.get(csvRecordData[0]);
tmpSet.add(Id.valueOf(csvRecordData[3]));
typeAccMap.put(csvRecordData[0], tmpSet);
}
}
else
{
Type__c t = new Type__c (Name = csvRecordData[3], Account__c = acc.id);
typeList.add(t);
typeAccMap.put(csvRecordData[0], new Set<String>{csvRecordData[3]});
}
}
insertupsert typeList;
}
}
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);
}
}
}