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
PrashantKPrashantK 

How to use Custom Field in Apex Code.

Hi All,

I have created Custom Field in Contact Object (Name: RegistrationAccount), but when I try to access it my Apex code its giving an error.

Code:

Contact c = new Contact(    
            AccountId=a.Id,
            FirstName = firstName,
            LastName = lastName,
            Account = a,
            Department = department,
            RegistrationAccount='UVA',   // My Custom Field
            Email = email,
            Phone=phone,
            Title = title,
            MailingStreet = streetAddress,
            MailingCity = cityAddress,
            MailingState = stateAddress,
            MailingPostalCode = postalCodeAddress,
            MailingCountry = countryAddress);

insert c;

 

Error: Compile Error: Invalid field RegistrationAccount for SObject Contact at line 45 column 33

Custom Field API Name :Registration Account_c

hitesh90hitesh90

Hi,

 

For custom field you have to append  "__c" at the last. means you have to take API Name of custom field.

 

Contact c = new Contact(    
            AccountId=a.Id,
            FirstName = firstName,
            LastName = lastName,
            Account = a,
            Department = department,
            RegistrationAccount__c ='UVA',   // My Custom Field
            Email = email,
            Phone=phone,
            Title = title,
            MailingStreet = streetAddress,
            MailingCity = cityAddress,
            MailingState = stateAddress,
            MailingPostalCode = postalCodeAddress,
            MailingCountry = countryAddress);
insert c;

 

Important :
Hit Kudos if this provides you with useful information and if this is what you where looking for then please mark it as a solution for other benefits.

Thank You,
Hitesh Patel
SFDC Certified Developer & Administrator

PrashantKPrashantK

Thanks for Replying...

I have used API name still it is not working...Is there any relationship or mapping require. Thanks in advance.

hitesh90hitesh90

No need for any relationship or mapping require here. what is the datatype of RegistrationAccount__c of this field?

Prafull G.Prafull G.
Could you please check FLS for for the desired Profiles?

If you are using the correct API name and the field is not visible then it will gives you the same error.

Hope it helps.
ForceMantis (Amit Jain)ForceMantis (Amit Jain)

As per your original error you are getting compile error which means you get error while you save code.

 

Reason API name is wrong

Fix - Use correct API name after checking in object defination

 

If you are getting run time error tell me exact error message and type of field?