+ Start a Discussion
Bhushan Singh 13Bhushan Singh 13 

How can we insert record into object from static resource during the loading visualforce page

Hi,
How can we insert record into object from static resource during the loading visualforce page.
e.g. I have one Object and created one visulaforce page, i want to insert the record from any static resource while that Visualforce is loading.
Please help me 

 
Alain CabonAlain Cabon
Hi,

It is a classic problem of serialization/deserialization. Salesforce often uses JSON as format.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_json_json.htm

Often used with callouts: https://trailhead.salesforce.com/fr/apex_integration_services/apex_integration_rest_callouts

Alain
V V Satyanarayana MaddipatiV V Satyanarayana Maddipati
Bhushan, you can query the static resource files from StaticResource Object as shown below : 
StaticResource sr = [select id, Body, ContentType, Name from staticresource where id = '08128000000PxiJ'];
String srBody = sr.Body.toString()); // parse the string by using Json deserialization methods.
To insert a record into an object while loading, currently salesforce won't allow you to perform DML operations inside the Static block and Constructor.

To Overcome this issue you can create action method and call it in the <apex:page> tag and perform DML operation inside the action method as shown below:
 
<apex:page controller="CustomController" action="{!insertData}">

</apex:page>

//Controller Code
public class CustomController {
    
    public CustomController() {
        
    }
    
    public void insertData() {
​         StaticResource sr = [select id, Body, ContentType, Name from staticresource where id = '08128000000PxiJ'];                       
         String srBody = sr.Body.toString()); // parse the string by using Json deserialization methods.
        //Perform DML opeartion here
         Account acc = new Account();
         acc.Name = 'Test';
         insert acc;
    } 
}

Thanks,
Satya.