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@awesomeemail.com' 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? :(

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@awesomeemail.com' limit 1];
        contactID = con.id;
        return  con.Name + ' ' + con.Email + ' ' + 'Title: ' + con.Title;
    }
  • 2
    Alternatively, you could use the getter syntax built into Apex: public String contactEmail{ get{ //logic to query and return string } } – James Loghry Oct 22 '12 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. – Bob Buzzard Oct 22 '12 at 21:19

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.