views:

250

answers:

2

N00b question:

I'm using Symfony with Doctrine. I have a form where I've added a little Jquery & Ajax check of whether a username that has been inputted into the form already exists. The jQuery calls a short PHP script on my web root that does the MySQL database check and returns true/false, which is then used to determine what error message to show.

However, if possible, I'd like to move the database call to a symfony helper function that then returns the true/false, rather having all the connection info etc on my web root. But I can't seem to be able to call the helper function correctly - all other components of the functionality work fine.

This is what I've got in my little php script:

$availability = GenericHelper::checkUsername();  // a public static function
echo $availability; // returns true/false to Jquery

Anyone? Thanks.

+2  A: 

Did you correctly load the helper?

sfContext::getInstance()->getConfiguration()->loadHelpers('Generic');

Then you should be able to call checkUsername() directly.

Or you can try to put GenericHelper.class.php to the lib/ directory, this way it will be auto-loaded.

Guillaume Flandre
Thanks Guillaume, tried that earlier, and tried now again with your exact code..... no effect. It doesn't return any error. It's just as if it does nothing.
Tom
... and yes, the class is in a lib/ folder already.
Tom
+1  A: 

Hi Tom,

Helpers are not meant for that sort of job (they are only meant for "view" related work, that is, generate html, etc).

Instead your should create an action (either in the same controller as your form or in a dedicated ajax controller, I personaly find the first option more easily maintenable) that will do the username check using a method of the model. See http://gist.github.com/286797 for a code example on how to do that (please note this code has not been tested and therefore could not work ootb).

You would then direct your Ajax query to that action.

Geoffrey Bachelet
Thanks Geoffrey, makes perfect sense. However, what I'm struggling to get my head around as a beginner is how that method call is most effectively achieved. I can't put it in the JQuery so I still need a php script fragment somewhere in my web root or deeper. Is that right?
Tom
No, what you need is to generate the url for your action and pass it to Jquery's ajax handler. I have updated the Gist at http://gist.github.com/286797 with simple routing and templating to reflect this :-)
Geoffrey Bachelet
Thanks Geoffrey, that's great.
Tom