Call a method in controller from Component (not in Constructor)-Visualforce

<apex:component>
 <apex:attribute name="l" description="l" type="double" assignTo="{!Received_L}"/>
  <apex:attribute name="varLng" description="t" type="double" assignTo="{!Received_T}"/>  
   //***** from here i want to call assignLocation()--------

</apex:component>

My Controller for Component

   public class myController {
         public double Recieved_L{get;set;}
         public double Recieved_T{get;set;}

         public myController(){
                //do initializations
          } //constructor        

    public PageReference assignLocation() {
        l=Recieved_L;
        t=Recieved_T;
        return null;
    }

I dont wanna call this method in constructor, I want to call myMethod() after page load. (Better if I am able to do this without using JavaScript/can also suggest)

Answer

I don’t know what you want to do after page is fully loaded so I will assume that you want to call a method to calculate a value using Received_T and Received_L.

You can use apex:actionFunction to call your calculation method. But you will need Javascript to run the method automatically after the page is loaded.

For example:

This is your page.

<apex:page>
    <c:mycomponent l="20" varLng="30" />
</apex:page>

This is your controller. In myMethod(), you calculate the value of calc_result.

 public class myControllerComponent {
 public double Received_L{get;set;}
 public double Received_T{get;set;}
 public double calc_result{get;set;}

public void myMethod() {
    this.calc_result = double.ValueOf(Apexpages.currentPage().getParameters().get('Received_T')) * double.ValueOf(Apexpages.currentPage().getParameters().get('Received_L'));
}      
}

In your component, you call javascript function when the page is loaded and pass both values to myMethod(). And then rerender div1 to see that calc_result shows up as 600.

<apex:component controller="myControllerComponent">
<script>
    onload = function() {
        myMethod('{!Received_T}', '{!Received_L}');
    }
</script>
<apex:attribute name="l" description="l" type="double" assignTo="{!Received_L}"/>
<apex:attribute name="varLng" description="t" type="double" assignTo="{!Received_T}"/> 
<apex:pageBlock title="My Custom Component">
    <p>
    <code>L</code> is "{!Received_L}"
    <br/>
    <code>T</code> is "{!Received_T}" <br/>
  </p>
  <apex:outputPanel id="div1">Result is "{!calc_result}"</apex:outputPanel >
</apex:pageBlock> 
<apex:form >
<apex:actionFunction name="myMethod" action="{!myMethod}" rerender="div1">
    <apex:param name="Received_T" value="" />
    <apex:param name="Received_L" value="" />
</apex:actionFunction>
</apex:form>
</apex:component>

Attribution
Source : Link , Question Author : Salesforce Steps , Answer Author : lw29

Leave a Comment