Monday, December 12, 2016

Visualforce - Beyond Basics Series 20 - Primitive types pass by value

How values passed to Component?

The values are passed to Component in runtime which means the values are assigned/type checked during execution.

How primitive types are handled ?

The primitive types like String, Number, Date passed to the Component as value. That means, when the client Page changes the value, component won't be affected.


What is the problem ?

Like some programming languages, developers expect the primitive types to be pass by reference. So, that they can change them in the called page any time, to reflect the changes in all the component using them. But, it doesn't work that way.

What is the solution ?

The solution is to use a Custom Class which will act as a wrapper/container for the primitive types.


Where is the code ?

This example illustrates how to pass a DateContainer object to the Component, so that when its value changed in the client page, it gets automatically changed inside the component.

public class testcls8_12122016 {
public MyDateContainer mdc {get; set;}
public testcls8_12122016() {
mdc = new MyDateContainer(System.Today());
}
public void addDay() {
mdc.myDate += 1;
}
}
view raw gistfile1.txt hosted with ❤ by GitHub
public class MyDateContainer {
public Date myDate {get; set;}
public MyDateContainer(Date d) {
this.myDate = d;
}
}
view raw gistfile1.txt hosted with ❤ by GitHub
<apex:component >
<apex:attribute type="MyDateContainer" name="myDate" description="Date container"/>
<apex:outputText value="Todays date is {!myDate.myDate}" style="font-size:25px;"/> <br/>
</apex:component>
view raw gistfile1.txt hosted with ❤ by GitHub
<apex:page controller="testcls8_12122016" >
<apex:form>
<c:testcmp8_12122016 myDate="{!mdc}" id="myComp"/>
<apex:commandButton value="Add one day" action="{!addDay}" reRender="myComp"/>
</apex:form>
</apex:page>
view raw gistfile1.txt hosted with ❤ by GitHub

No comments:

Post a Comment

Thanks for reading my blog !