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
naypers rtfnaypers rtf 

Create a SOQL record from code

Hi!, I hope someone can help me.

 

I'm creating a function to check if I have a record in a SOQL table, I using a custom object, my app will need a 'Default' record to work, if this record doesn't exist, I'd like to create it from here.

 

I have something like this, but this function doesn't create the record and I dont know why.

 

    public void checkDefault(){

        try{ 
        
	// If is possible to do this, it means I have a record 'Default'.
        customObject__c obj = [ SELECT Concept1__c,Concept2__c,Concept3__c,Concept4__c  FROM customObject__c WHERE name='Default' LIMIT 1 ];
        update obj;  

        } 
		
	// If I don't have it... create it.
         catch(Exception ex){ 

             customObject__c obj = new customObject__c(
                name='Default',
                Concept1__c = ' Text ',
                Concept2__c = ' Text ',
                Concept3__c = ' Text ',
                Concept4__c = ' Text ');
        }
            
    }

 

Please help!

NaypersMclgxNaypersMclgx

Only you need to add  "Database.upsert(obj);" after defining the object

 

    public void checkDefault(){

        try{ 
        
	// If is possible to do this, it means I have a record 'Default'.
        customObject__c obj = [ SELECT Concept1__c,Concept2__c,Concept3__c,Concept4__c  FROM customObject__c WHERE name='Default' LIMIT 1 ];
        update obj;  

        } 
		
	// If I don't have it... create it.
         catch(Exception ex){ 

             customObject__c obj = new customObject__c(
                name='Default',
                Concept1__c = ' Text ',
                Concept2__c = ' Text ',
                Concept3__c = ' Text ',
                Concept4__c = ' Text ');

Database.upsert(obj);

} }