4

I was surprised recently when a Visualforce component was able to overwrite the value of a variable used in another component. Here's a stripped down version of what I saw:

Sample.page

<apex:page>
    <c:foo title="title for foo"/>
    <c:bar/>
</apex:page>

foo.component

<apex:attribute name="title" type="String"/>
<apex:outputPanel id="fooPanel">
    {!title}
    <apex:form>
        <apex:actionFunction name="fooAction" action="{!foo}" rerender="fooPanel"/>
    </apex:form>
    <button onclick="fooAction();"\>
</apex:outputPanel>

bar.component

<apex:variable var="title" value="some new value">

So after the page rendered, I clicked the button, which called fooAction() and was surprised when the title changed!

Is this expected behavior? Should I be doing something to keep the title of foo.component separate from the title of bar.component? What about best practices for variable naming in components -- prefix all local variable names with something related to the component?

2

Components are supposed to be re-usable pieces of Visualforce so when the page is rendered they're built straight into it. They could have used a namespace setup to avoid collisions such as this but I suspect just as many people would want the ability to create reusable pieces of code which depend on existing variables.

With regards to avoiding the issue I'd say using a naming convention as you suggest would be the best way forward, use a simple, unique prefix for all variables in each component.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.