[SalesForce] Create static resource with apex code

Is there a way to create a StaticResource within a Apex code.

this the code i am doing:

        StaticResource sr = new StaticResource();
        sr.Body = file;
        sr.Name = 'testLicence';
        sr.ContentType = 'zip';
        sr.CacheControl = 'Public';

        sr.create();

but i am getting this error:

Method does not exist or incorrect signature: [StaticResource].create

and when i consulted the documentation in this link: StaticResource Documentation

it says that the create() method is supported.

What's wrong with my code ?

Best Answer

You will have to go with MetaData API. Something as below -

    MetadataService.MetadataPort service = createService();     
    MetadataService.StaticResource staticResource = new MetadataService.StaticResource();
    staticResource.fullName = 'MyResource';
    staticResource.contentType = 'text';
    staticResource.cacheControl = 'public';
    staticResource.content = EncodingUtil.base64Encode(Blob.valueOf('Static stuff'));
    MetadataService.AsyncResult[] results = service.create(new List<MetadataService.Metadata> { staticResource });

Remember that each create call corresponds to a callout. Here is a brilliant repository on Metadata API that can help you out.

https://github.com/financialforcedev/apex-mdapi

Related Topic