Monday, 26 September 2011

Change Feature Image in Sandbox Solutions.


So recently, I had created a sandbox solution which deployed a Web Part when the feature associated with my solution was activated. So I thought when the user navigated to the Manage Features page, it should be easier for him/her to recognize which feature has to be activated and decided to assign an custom image to it.

Now my first thought was to deploy an image from the solution and assign its relative URL to the ImageUrl property of the feature. So, I deployed my custom image to the path /myFolder/awesome_img.png and assigned the same relative URL to my feature’s ImageUrl property.

And when I navigated to the Manage Features page, I was greeted with the following:


It turned out that SharePoint by default looks for the assigned image in the /_layouts/images/ folder. So whichever URL I provided to the ImageUrl property, SharePoint appended the /_layouts/images in front of it and assigned it to my feature.

Now since we are in the Sandbox, we do not have access to the _layouts folder. So we cannot deploy our custom Image to the folder and assign it to the feature.

But there is a workaround...and JavaScript has the answer!

So what I did was:
1) Deployed my custom Image to one of my SharePoint libraries.

2) Assigned place holder text to the ImageUrl property of the feature.


3) Wrote this little jQuery script which checked for the place holder text and replaced it with the path to my custom image.


jQuery(document).ready(function () {

      //Check if the current page is the Manage Features page.
     if (location.href.indexOf("ManageFeatures.aspx") != -1) {
           
          //Fetch each image with the place holder as the src.
         jQuery("img[src*='myFeatureImagePlaceHolder']").each(function () {
           
            //Replace the src of the image.
            this.src = this.src.replace("/_layouts/images/myFeatureImagePlaceHolder", _spPageContextInfo.siteServerRelativeUrl + "/myFolder/awesome_img.png");
          
        });
    }
});


4) Using Script delegates, Embedded the jQuery library and my custom JavaScript file into the masterpage, So that they will be available on the Manage Features page.


xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

<CustomAction Location="ScriptLink" ScriptSrc="~SiteCollection/Scripts/jquery-1.6.min.js" Sequence="1004" />

<CustomAction Location="ScriptLink" ScriptSrc="~SiteCollection/Scripts/ReplaceFeatureIcon.js" Sequence="1005"/>
<Elements>


After deploying the solution, I navigated to the Manage Features page and Voila! The feature image had changed:

1 comment:

Anonymous said...

There is a much simpler solution. Simply use a relative path, e.g. "../../myFolder/awesome_img.png"