Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Wednesday, July 12, 2023

Access Static Resource in Visualforce Page

 Accessing salesforce static resource depends on the whether you want access standalone single file or you can access file with in archive such as .zip

          1. You want access stand alone single file means use $Resource.filename. here filename indicate which file you want to import in visualforce page. We want to use  $Resource.filename with this {!}. other wise it throw the error
the example is given below,

            <apex:image url="{!$Resource.CoffeeImage}" />

or
we can access using URLFOR to access the static resource

            <script type="text/javascript" src="{!URLFOR($Resource.Mainjs)}"/>


         2. Access static resource from the archive means use URLFOR function. this first parameter used to point out the archive name and second parameter used to indicate the file name which are available inside the archive.
 the example is given below

            <img src="{!URLFOR($Resource.images,'images/icons/minus.png')}" alt="pathnotFound" width="50" height="50"/>



         3. We can use relative path to access the archive file to show in page. In CSS we can access the archive file using the relative path concept. The style.css  to have one line code for set background image it need to refer the archive file called minus.png. the code is given below.

            background-image: url(../images/images/icons/minus.png);


the minus.png file available in images.zip static resource archive. the above code to get the image from that archive and set the background for where we set.

          4. We can access static resource dynamically through a custom controller, the example is given below

            global class MyController {
                 public String getName() {
                           return "sample.png";
                   }
            }


Then referer the getName() function in visualforce page using <apex:variable> tag

            <apex:variable var="imageName" value={!name}/>
            <apex:image url="{!URLFOR($Resource.zipfile, imageName)}"/>


you want to change the file name means to change getName() function return value

No comments:

Post a Comment