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
MRITYUNJAY PATEL 3MRITYUNJAY PATEL 3 

how to insert new record in custom setting object field using Apex

Best Answer chosen by MRITYUNJAY PATEL 3
sakhisakhi
Hi Mrityunjay,

Like custom objects , custom settings also have name as required field by default which can later be used to get data as key value pair Hence It is
important to provide name to custom setting while creating a record .
Following code should work for you if you have no other required field other than name .
 
API_KEY__c ak=new API_KEY__c(Name= 'TESTKEY1',keys__c = 'Test1');
insert ak;

Please mark it best answer if it solves.
 

All Answers

jobsvjobsv
You can insert like a record:
 
MyCustomSetting__c myCustomSetting = new MyCustomSetting__c();
myCustomSetting.Field_1__c = 'A';
myCustomSetting.Field_2__c = 5;
insert myCustomSetting;

 
MRITYUNJAY PATEL 3MRITYUNJAY PATEL 3
Hey  jobsv,
thanks for replying , but i have error 
this is my code for insert the record on keys__c field

API_KEY__c ak=new API_KEY__c(keys__c = 'Test');
insert ak;

Line: 3, Column: 1
System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Name]: [Name]
Suraj Tripathi 47Suraj Tripathi 47
Hi,
Please provide a name when you are inserting API_KEY__c.
API_KEY__c ak=new API_KEY__c(Name='test1', keys__c = 'Test');
Insert ak;

Please mark it as Best Answer if it helps you.

Thanks & Regards
Suraj Tripathi
sakhisakhi
Hi Mrityunjay,

Like custom objects , custom settings also have name as required field by default which can later be used to get data as key value pair Hence It is
important to provide name to custom setting while creating a record .
Following code should work for you if you have no other required field other than name .
 
API_KEY__c ak=new API_KEY__c(Name= 'TESTKEY1',keys__c = 'Test1');
insert ak;

Please mark it best answer if it solves.
 
This was selected as the best answer
Aditya NarwadeAditya Narwade
public class CustomSettingTest {
    public static void myMethod(){
        Narwade_Constructions__c newobj = new Narwade_Constructions__c();
        newobj.name = 'Aditya';
        newobj.Empolyee_Name__c = 'Narwade';
        newobj.Employee_Age__c = '40';
        newobj.Employee_Salary__c = '750000';
        insert newobj;
    }
}
Refer this code for insert record. Name field is mandatory in custom setting. 

Thanks & Regards
Aditya Narwade