function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
LavanyaLavanya 

Checking duplicate Account name uploading a csv file to create new Account, contact Apex

Hi all , when i am uploading csv file to create a new account, conatct and oppotunity i need to check account duplicate name. If not exist i need to create new  account else it must show the error message that account name already exist. i need to achevie this uiong apex code. Kindly anyone tell how to resolve this.

 

Apex code:

 

public class FileUploaderAll
{

public FileUploaderAll(ApexPages.StandardController controller) {

}


public PageReference fileAccess() {
return null;
}


public FileUploaderAll(){

}
public string nameFile{get;set;}
public Blob contentFile{get;set;}
String[] filelines = new String[]{};
List<Account> accstoupload;
List<Contact> contoupload;
List<Opportunity> opptoupload;
List<CustomLead__c> custtoupload;

public Pagereference ReadFile()
{
nameFile=contentFile.toString();
filelines = nameFile.split('\n');
accstoupload = new List<Account>();
contoupload = new List<Contact>();
opptoupload = new List<Opportunity>();
custtoupload = new List<CustomLead__c>();
for (Integer i=1;i<filelines.size();i++)
{
String[] inputvalues = new String[]{};
inputvalues = filelines[i].split(',');


Account a = new Account();
a.Name = inputvalues[0];

accstoupload.add(a);
}
try
{
insert accstoupload;
}
catch (Exception e)
{
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later');
ApexPages.addMessage(errormsg);
}

//return null;
for (Integer i=1;i<filelines.size();i++)
{
String[] inputconvalues = new String[]{};
inputconvalues = filelines[i].split(',');

Contact con = new Contact();
for(account a: accstoupload)
{
con.AccountId = accstoupload[i-1].id;
//con.AccountId = a.Id;
}
//con.Account= inputconvalues[0];
con.Lastname = inputconvalues[1];
con.Lastname_lead__c = inputconvalues[2];

contoupload.add(con);
}

try
{
insert contoupload;
}
catch (Exception e1)
{
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later');
ApexPages.addMessage(errormsg);
}
// return null;

for (Integer i=1;i<filelines.size();i++)
{
String[] inputvalues = new String[]{};
inputvalues = filelines[i].split(',');

Opportunity opp = new Opportunity();
for(account a: accstoupload)
{
opp.AccountId = accstoupload[i-1].id;
//opp.AccountId = a.Id;
}
opp.Name = inputvalues[3];
opp.OPP_DateOfBirth__c = inputvalues[4];
opp.StageName = inputvalues[6];
opp.CloseDate = date.parse(inputvalues[5]);
// a.ShippingPostalCode = inputvalues[4];
// a.ShippingCountry = inputvalues[5];

opptoupload.add(opp);
}

try
{
insert opptoupload;
}
catch (Exception e2)
{
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later');
ApexPages.addMessage(errormsg);
}
for (Integer i=1;i<filelines.size();i++)
{
String[] inputcustvalues = new String[]{};
inputcustvalues = filelines[i].split(',');


CustomLead__c cust = new CustomLead__c();
cust.CompanyName__c = inputcustvalues[0];
cust.LastName_c__c = inputcustvalues[1];
cust.Name = inputcustvalues[2];
cust.opp_name__c = inputcustvalues[3];

custtoupload.add(cust);
}
try
{
insert custtoupload;
}
catch (Exception e3)
{
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later');
ApexPages.addMessage(errormsg);
}
return null;
}
public List<Account> getuploadedAccounts()
{
if (accstoupload!= NULL)
if (accstoupload.size() > 0)
return accstoupload;
else
return null;
else
return null;
}

public List<Contact> getuploadedContact()
{
if (contoupload!= NULL)
if (contoupload.size() > 0)
return contoupload;
else
return null;
else
return null;
}

public List<Opportunity> getuploadedOpportunity()
{
if (opptoupload!= NULL)
if (opptoupload.size() > 0)
return opptoupload;
else
return null;
else
return null;
}
public List<CustomLead__c> getuploadedCustomLead()
{
if (custtoupload!= NULL)
if (custtoupload.size() > 0)
return custtoupload;
else
return null;
else
return null;
}
/* public pageReference fileAccess(){
Document lstDoc = [select id,name,Body from Document where name = 'test'];

System.Debug('DOC NAME :: '+lstDoc.name);
System.Debug('DOCBODY :: '+lstDoc.Body);


return null;
} */

public static testMethod void testReadFile1() {

Document lstDoc = [select id,name,Body from Document where name = 'test'];

// System.Debug('DOC NAME :: '+lstDoc.name);
//System.Debug('DOCBODY :: '+lstDoc.Body);
FileUploader file=new FileUploader();
Blob content= lstDoc.Body;
file.nameFile=content.toString();

}

public static testMethod void testReadFile2() {

}

}

 

Best Answer chosen by Admin (Salesforce Developers) 
ForcepowerForcepower

Lavanya.

 

As part of your loop to read accounts, put the account names into a List<String> acctNames.

 

Then you retrieve all existing accounts matching these names before the insert code

List<Account> existingAccts = [SELECT Id, Name FROM Account
where name in :acctNames];

 

//create a map with names as key

Map<String, Id> acctNamesIdMap = new Map<String, Id>();

// load the map - this will help you find out if an account name exists already

for (Account acct : existingAccts) {

      acctNamesIdMap.put(acct.Name, acct.Id);

}

List<Account> newAccts = List<Account>();

for (Account acct : accstoupload) {

      //if account name does not exist in map, add it to list of new accounts

      if (!acctNamesIdMap.containsKey(acct.Name)) {

               newAccts.add(acct);

       }

}

try
{
//insert accstoupload;

insert newAccts;
}

All Answers

udayar_jayamudayar_jayam

I have the same issues 

LavanyaLavanya
Udayar_jayam, if so tell me the code for this
ForcepowerForcepower

Lavanya.

 

As part of your loop to read accounts, put the account names into a List<String> acctNames.

 

Then you retrieve all existing accounts matching these names before the insert code

List<Account> existingAccts = [SELECT Id, Name FROM Account
where name in :acctNames];

 

//create a map with names as key

Map<String, Id> acctNamesIdMap = new Map<String, Id>();

// load the map - this will help you find out if an account name exists already

for (Account acct : existingAccts) {

      acctNamesIdMap.put(acct.Name, acct.Id);

}

List<Account> newAccts = List<Account>();

for (Account acct : accstoupload) {

      //if account name does not exist in map, add it to list of new accounts

      if (!acctNamesIdMap.containsKey(acct.Name)) {

               newAccts.add(acct);

       }

}

try
{
//insert accstoupload;

insert newAccts;
}

This was selected as the best answer
LavanyaLavanya

Hi Ram thanks for the reply. After made these changes my look like this

 

for (Integer i=1;i<filelines.size();i++)
{
String[] inputvalues = new String[]{};
inputvalues = filelines[i].split(',');


Account a = new Account();
a.Name = inputvalues[0];

accstoupload.add(a);
}
List<Account> existingAccts = [SELECT Id, Name FROM Account
where name in :acctNames];
//create a map with names as key
Map<String, Id> acctNamesIdMap = new Map<String, Id>();
// load the map - this will help you find out if an account name exists already
for (Account acct : existingAccts) {
acctNamesIdMap.put(acct.Name, acct.Id);
System.debug('******Sai******');
}

//List<Account> newAccts = new List<Account>();
for (Account acct : accstoupload) {
//if account name does not exist in map, add it to list of new accounts
if (!acctNamesIdMap.containsKey(acct.Name)) {
newAccts.add(acct);

}
}
try
{
//insert accstoupload;
insert newAccts;
}
catch (Exception e)
{
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later');
ApexPages.addMessage(errormsg);
}

 

i am getting this error.
Attempt to de-reference a null object
Error is in expression '{!ReadFile}' in component <apex:page> in page uploadaccountsall

ForcepowerForcepower
Lavanya, I don't see where you loaded acctNames with the names. That should happen in the loop that contains this:
a.Name = inputvalues[0];
acctNames.add(a.Name);
Ram
LavanyaLavanya

Hi Ram, thanks for the reply, it helped me a lot. But i am the same erreor, after i made these changes in my code look like this. I tried a lot but i can't resolve this error.

Error Msg:

Attempt to de-reference a null object
Error is in expression '{!ReadFile}' in component <apex:page> in page uploadaccountsall

 

Code:

 

List<String> acctNames;

public Pagereference ReadFile()
{
nameFile=contentFile.toString();
filelines = nameFile.split('\n');
accstoupload = new List<Account>();
contoupload = new List<Contact>();
opptoupload = new List<Opportunity>();
custtoupload = new List<CustomLead__c>();

for (Integer i=1;i<filelines.size();i++)
{
String[] inputvalues = new String[]{};
inputvalues = filelines[i].split(',');
Account a = new Account();
a.Name = inputvalues[0];
acctNames.add(a.Name);

accstoupload.add(a);
}

List<Account> existingAccts = [SELECT Id, Name FROM Account where name in :acctNames];
//create a map with names as key
Map<String, Id> acctNamesIdMap = new Map<String, Id>();
// load the map - this will help you find out if an account name exists already
for (Account acct : existingAccts)
{
acctNamesIdMap.put(acct.Name, acct.Id);
System.debug('******Sai******');
}
List<Account> newAccts = new List<Account>();
for (Account acct : accstoupload)
{
//if account name does not exist in map, add it to list of new accounts
if (!acctNamesIdMap.containsKey(acct.Name))
{
newAccts.add(acct);

}
}

try
{
//insert accstoupload;
insert newAccts;
}
catch (Exception e)
{
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later');
ApexPages.addMessage(errormsg);
}

public List<Account> getuploadedAccounts()
{

if (accstoupload!= NULL)
if (accstoupload.size() > 0)
return accstoupload;
else
return null;
else
return null;

 

 Kindly reply me to resolve this.

Thanks,

Lavanya.

ForcepowerForcepower
Lavanya,
You need to make sure to initialize all your lists before using them. Try
accctNames = new List<String>() before the for loop that uses it.
Ram
LavanyaLavanya

Hi Ram, Its working thanks a lot. But one more issue i am getting is once the account exist, if i upload the same csv file again it must give the error msg "Account Already Exist".I have given the error code in Catch but its not working.Kindly anyone tell how to get this

Code:

for (Integer i=1;i<filelines.size();i++)
{
String[] inputvalues = new String[]{};
inputvalues = filelines[i].split(',');
Account a = new Account();
a.Name = inputvalues[0];
acctNames.add(a.Name);

accstoupload.add(a);
}
List<Account> existingAccts =new List<Account>();

existingAccts = [SELECT Id, Name FROM Account where name in :acctNames];
//create a map with names as key
Map<String, Id> acctNamesIdMap = new Map<String, Id>();
// load the map - this will help you find out if an account name exists already
for (Account acct : existingAccts)
{
acctNamesIdMap.put(acct.Name, acct.Id);
System.debug('******Sai******');
}

for (Account acct : accstoupload)
{
//if account name does not exist in map, add it to list of new accounts
if (!acctNamesIdMap.containsKey(acct.Name))
{
newAccts.add(acct);

}
}

try
{
//insert accstoupload;
insert newAccts;
}
catch (Exception e)
{

ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'Account Name already exist, change Account Name and try again');
ApexPages.addMessage(errormsg);
}

Regards,

Lavanya

 

ForcepowerForcepower

Lavanya,

 

I wouldn't say it is necessarily an error for someone to supply an existing account name as they may be trying to add a new contact to that acount. In any case, if your accounts and contacts are strictly one-to-one and if you want it to fail on these dup accounts and contacts, try this:

 

for (Account acct : existingAccts)
{
acctNamesIdMap.put(acct.Name, acct.Id);
System.debug('******Sai******' + acct.Name);
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'Account ' + acct.Name + ' already exists, change Account Name and try again');
ApexPages.addMessage(errormsg);
}