2
votes

I have a Salesforce object, lets say Contact.
If I try to set the Name field by using code:

   Contact testAccount = new Contact();
   testAccount.Name ='TestAccountContact';        
   insert testAccount;  

It gives an error:

Line: 2, Column: 20 Field is not writeable: Contact.Name

By navigating the object through Salesforce I find that Name is a combination of FirstName, LastName.
How can I determine if the field is writeable and if not get the componenets of that field that together represent it. In this case FirstName and LastName cconcatenated makes up Name.

1

1 Answers

1
votes

Contact/Lead/User Name is special field which Salesforce composes in runtime depending on what's in the data and who's looking. Source fields can be:

  1. Salutation (Mr, Mrs...)
  2. FirstName
  3. MiddleName (if you have them enabled)
  4. LastName
  5. Suffix (if you have them enabled)

"Who's looking"? There are cultures that use "LastName FirstName", commonly referred to as CJK (Chinese,Japanese,Korean) but also Hungarian for example. This is defined by user's locale.

To check if field can be written to on insert use "describe" calls, specifically isCreateable.

System.debug(Schema.sObjectType.Contact.fields.Name.isCreateable()); // false

For practical purposes - try to not to use Contact.Name too much in Apex or reports for example. You'll forget this quirk and 2 years later will get a "funny" bug report that for some user report that goes Name equals to John Doe doesn't return any results for certain user and you'll go all "works for me".