Thursday 9 January 2014

Convert existing contact to person account???

we just enabled person account on the contact object, but there are lots of existing contacts do not have any 1 to 1 person account on account object.
So use this code to create person accounts for these existing contact without deleting these contacts, as these contacts were referenced by different objects;

//get the business account record type
RecordType NotPersonAccountRecordType = [select Id, Name, SobjectType,
         IsPersonType from RecordType where SobjectType='Account'
         and IsPersonType=False];

// get 1 existing account
Contact c = [select id, AccountId, FirstName, LastName from Contact where IsPersonAccount = false Limit 1];

// create a new account and set the record type to business account
Account newAccount = new Account();
newAccount.Name='' + c.LastName;
newAccount.RecordTypeId = NotPersonAccountRecordType.Id;
insert newAccount;

//get the person account record type
recordType personaccountrecordtype = [select Id, Name, SobjectType,
         IsPersonType from RecordType where SobjectType='Account'
         and IsPersonType=True];

// update the existing contact's account to new account
c.AccountId = newAccount.Id;
update c;

// now get it again and update the firstname and lastname, change the record type to person account
newAccount = [select id,lastName, Firstname, RecordTypeId from Account where Id =: newAccount.Id];
newAccount.RecordTypeId = personaccountrecordtype.Id;
update newAccount;



(OR)


RecordType personaccountrecordtype = [select Id, Name, SobjectType,IsPersonType from RecordType where SobjectType='Account' and IsPersonType=True];
Contact c = [select id, AccountId, FirstName, LastName,Birthdate,Phone from Contact where IsPersonAccount = false limit 1];
               
Account newPersonAccount = new Account();
newPersonAccount.Name=(c.FirstName+c.LastName);
newPersonAccount.Phone=c.phone;

insert newPersonAccount;
 

c.AccountId=newPersonAccount.Id;
update c;
 

newPersonAccount=[select id,lastName, Firstname, RecordTypeId from Account where Id =:newPersonAccount.Id];               
newPersonAccount.RecordTypeId=personaccountrecordtype.Id;

update newPersonAccount;

 

No comments:

Post a Comment