I always enjoy the logical thinking required for programming. For Symfony it is really nice how it all just flows together. I wanted to implement an ajax check for unique usernames. Something similar like how you see it on Twitter. Lets get started:
First create a validator in lib/validators/sfUniqueUserValidator.class.php
<?php class sfUniqueUserValidator extends sfValidator { public function execute (&$value, &$error) { //check if the username exists $c = new Criteria(); $c->add(sfGuardUserPeer::USERNAME, $value); $user = sfGuardUserPeer::doSelect($c); if (!empty($user)) { $error = $this->getParameter('user_error'); return false; } return true; } public function initialize ($context, $parameters = null) { // Initialize parent parent::initialize($context); // Set default parameters value $this->setParameter('user_error', 'This username is taken'); // Set parameters $this->getParameterHolder()->add($parameters); return true; } }
Then in your view template use:
<?php echo observe_field('rusername', array( 'update' => 'userstatus', 'url' => 'sfGuardAuth/checkuser', 'with' => "'id='+$('rusername').value", )) ?>
this will monitor an input field called rusername, and submit its value to the sfGuardAuth/checkuser internal url.
And to glue it all together, in the actions:
public function executeCheckuser() { $username = $this->getRequestParameter('id'); $userValidator = new sfUniqueUserValidator(); $userValidator->initialize($this->getContext()); $error='none'; if (!$userValidator->execute($username,$error)) return $this->renderText($username.' is taken'); return $this->renderText($username.' is available'); }
Enjoy!
Ps. any tips for posting code in wordpress would be greatly appreciated, for me it does the strangest types of things.