8

You would think this would be more obvious, but "how can I call a method from a visualforce page?"

Say I have something like this:

<apex:page controller="PreChatController ">
  <script>
    <apex:repeat value="{!ContactFromEmail}">
    </apex:repeat>    
  </script>
</apex:page>

And here is ContactFromEmail in a controller:

public String ContactFromEmail()
    { 
        Contact con = [SELECT id, Email, Name, Title FROM Contact where Email = '[email protected]' limit 1];
        contactID = con.id;
        return  con.Name + ' ' + con.Email + ' ' + 'Title: ' + con.Title;
    }

You would think this would be easy, but it doesn't seem to be. I don't want the string to be a property I have to set. I just want to invoke a method call. What am I doing wrong? :(

1 Answer 1

13

In order to be able to retrieve data in this way, your method needs to be a getter, as there's an implicit 'get' added by Visualforce. You don't need a way to set it as you aren't binding any inputs to it. There's also no reason to use an apex:repeat, as this is for iterating a collection (though I think that it would work with a single value).

You can output the string to the page via:

<apex:outputText value="{!ContactFromEmail}" />

and the controller:

public String getContactFromEmail()
    { 
        Contact con = [SELECT id, Email, Name, Title FROM Contact where Email = '[email protected]' limit 1];
        contactID = con.id;
        return  con.Name + ' ' + con.Email + ' ' + 'Title: ' + con.Title;
    }
2
  • 2
    Alternatively, you could use the getter syntax built into Apex: public String contactEmail{ get{ //logic to query and return string } } Commented Oct 22, 2012 at 18:47
  • 3
    I try to avoid that if the getter is doing real work, as I think it can make the class more difficult to read and understand. Commented Oct 22, 2012 at 21:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .