![]() |
|
Snippets |
|
Symfony 1.1 comes with a complete new form system. It works completely according to the MVC draft:
Make sure you have a running Symfony 1.1 based project and application and modules. In this example I build the form inside the myModule module and myLogin action.
My form makes use of i18n, which is in my case autoloaded in settings.yml.
This tutorial uses Symfony 1.1 beta4 and RC1. There are a little important changes with respect to beta3, which I don't cover.
I also expect you to have practical knowledge and a little bit experience with Symfony as system. I will not explain how you i18n implements or modules shield with security.yml.
The form gets two import fields: username and password. Furthermore is there a hidden field in which the URI comes that the user requested, but got redirected to the loginform (through Symfony’s security.yml and settings.yml). This will be used to go to that URI again after a successful login.
Both imput fields are required I will build a custom validation for a correct username/password check. Also we want to make use of a little new protection feature: CSRF.
The form takes uses i18n for multilinguity, I will use English primarily, but the view has been prepared for other languages.
We will begin with the action which contains the primary control.
/** * Executes myLogin action * * Login functionality. * * @param void * @return void * @access public */ public function executeMyLogin() { // Erase auth data $this->getUser()->clearCredentials(); $this->getUser()->setAuthenticated(FALSE); // Build login form $oForm = new inloggenForm(); if ($this->getRequest()->isMethod('post')) { // When called through POST (form submit) $oForm->bind( array('username' => $this->getRequest()->getParameter('username'), 'password' => $this->getRequest()->getParameter('password'), 'referrer' => $this->getRequest()->getParameter('referrer'), ) ); // Save orginal requested location in referrer field $oForm->setDefault('referrer', $this->getRequest()->getParameter('referrer')); if ($oForm->isValid()) { // When validations OK $aValues = $oForm->getValues(); sfContext::getInstance()->getLogger()->debug($aValues['username']); // Authentification $this->getUser()->setAuthenticated(TRUE); // To requested page $this->redirect($this->getRequest()->getParameter('referrer')); } } else { // Save original requested uri in form $oForm->setDefault('referrer', sfContext::getInstance()->getRequest()->getUri()); } $this->oForm = $oForm; // form to view }
Logic of authentification is set after POST further. Through the sfForm::bind() method couples the input of the user coupled with the form controller.
I made this in myModule/lib/form/inloggenForm.class.php. In the form is defined and coupled with the validations and the formatting.
<?php class inloggenForm extends sfForm { /** * Prepare validators */ private function _setValidators() { $this->oValGebruikersnaam = new sfValidatorAnd( array( new sfValidatorString(array('min_length' => 3, 'max_length' => 50), array('min_length' => 'The username should be at least three characters long', 'max_length' => 'The username should be fifty characters long at most', ) ), new sfValidatorCallback(array('callback' => array('cmsLoginValidator', 'execute'), 'arguments' => array() ), array('invalid' => 'This username/password combination is unknown') ), ), array('required' => TRUE), array('required' => 'The username is mandatory') ); $this->oValWachtwoord = new sfValidatorString(array('required' => TRUE), array('required' => 'The password is mandatory') ); $this->oValReferrer = new sfValidatorString(array('required' => FALSE)); } /** * Prepare widgets */ private function _setWidgets() { $this->oWidGebruikersnaam = new sfWidgetFormInput(array(), array('id' => 'username', 'size' => 25)); $this->oWidWachtwoord = new sfWidgetFormInputPassword(array(), array('id' => 'password', 'size' => 10)); $this->oWidReferrer = new sfWidgetFormInputHidden(array(), array('id' => 'referrer')); } /** * Configure form */ public function configure() { $this->_setValidators(); $this->_setWidgets(); /* * Set validators */ $this->setValidators(array('username' => $this->oValGebruikersnaam, 'password' => $this->oValWachtwoord, 'referrer' => $this->oValReferrer, ) ); /* * Set widgets */ $this->setWidgets(array('username' => $this->oWidGebruikersnaam, 'password' => $this->oWidWachtwoord, 'referrer' => $this->oWidReferrer, ) ); /* * Set decorator */ $oDecorator = new sfWidgetFormSchemaFormatterDiv($this->getWidgetSchema()); $this->getWidgetSchema()->addFormFormatter('div', $oDecorator); $this->getWidgetSchema()->setFormFormatterName('div'); $this->getWidgetSchema()->setHelps(array('username' => 'Please enter your username', 'password' => 'Please enter your password' ) ); } /** * Bind override */ public function bind(array $taintedValues = null, array $taintedFiles = array()) { $request = sfContext::getInstance()->getRequest(); if ($request->hasParameter(self::$CSRFFieldName)) { $taintedValues[self::$CSRFFieldName] = $request->getParameter(self::$CSRFFieldName); } parent::bind($taintedValues, $taintedFiles); } }
There are two private methods:
I overloaded the earlier mentioned bind() method to process the CSRF token internally. This fiels is regulated by sfForm internally, you to do need to worry about it much, only with the actual functionality.
The configure() method contains the functionality. The validators are created and linked to the corresponding fields and also are the widgets. Also, the decorator is defined with I will go into later on.
In _setValidators() sfValidatorBase objects are made for each field.
The password field check is the simplest, only the required input is checked. The object is of the type sfValidatorString (extend sfValidatorBase) without extra controls, only the required attribute with errortext is specified. In principle, you can use each validator as -empty- container.
The username is a combination; it is required, there are restrictions to the the stringlength and a correct login is checked. The stringcontrole/requirement is checked through sfValidatorString, which is quite simple.
The check for a correct login is done through a special validator, that does a callback to an custom function: sfValidatorCallback. This is explained later.
Since these two validators check the same field , the sfValidatorAnd validator is used that combines several validators. All validators must be satisfied. Of course Symfony also offers sfValidatorOr that checks that at least one underlying validator satisfies.
As you can see the callback validator calls to a custom class/method: myLoginValidator::execute().
/** * Fiel with myLoginValidator klasse * * @package - */ /** * Validation correct username/password * * @author Jordi Backx (Snowkrash) * @copyright Copyright © 2008, Jordi Backx (Snowkrash) * @package - */ class myLoginValidator { /** * execute validator * * @param sfValidatorBase Validator instance that calls this method * @param string Value of field that sfValidatorCallback checks * @param array Arguments for correct working * * @return value field when OK. Nothing if error (sfValidatorError exception) */ public static function execute ($oValidator, $sValue, $aArguments) { if ( /* check OK */ ) { // Return waarde veld indien controle OK return $sValue; } // Throw exception when not OK throw new sfValidatorError($oValidator, 'invalid', array('value' => $sValue, 'invalid' => $oValidator->getOption('invalid'))); } }
I set this here with no further logic, that is application specific, thus that you 'll have to do yourself. The base structure can be used. The three parameters must be defined, otherwise the whole application crashes.
In _setWidget() sfWidget objects are made for each field.
The widgets are the form elements: finally <input>, <select> etc tags in combination with labels and errortexts.
Each widget can have HTML attributes, which will be printed inside the form elements.
Finally the form must be printed to the screen through a view template.
<p><?php echo __('You need to log in to be able to use the Content Management System.') ?></p> <div id="formContainer"> <?php if ($oForm->getErrorSchema()->getErrors()) { ?> <div id="formulierFouten"> <ul> <?php foreach ($oForm->getErrorSchema() as $sError) { ?> <li><?php echo __($sError) ?></li> <?php } ?> </ul> </div> <?php } ?> <form action="<?php echo url_for('myModule/myLogin') ?>" method="post"> <?php echo $oForm['username']->renderLabel(__($oForm['username']->renderLabelName())); echo $oForm['username']->renderRow(__($oForm->getWidgetSchema()->getHelp('username'))); ?> <?php echo $oForm['password']->renderLabel(__($oForm['password']->renderLabelName())); echo $oForm['password']->renderRow(__($oForm->getWidgetSchema()->getHelp('password'))); ?> <?php echo $oForm['referrer']->render(array('value' => $oForm->getDefault('referrer'))) ?> <?php echo $oForm['_csrf_token'] ?> <label for="inloggen"> </label><input type="submit" value="Inloggen" id="inloggen" class="aanmeldenSubmit" /> </form> </div>
You can see all the i18n code (__() helper) and some non-Symfony 1.0 form building. Errorlists are built through the errorSchema which is available within the form object, the texts themself can be translated as you can see.
Also the labels and help texts are squeezed through i18n. The field names are in English, because the labels are based on these and must go through i18n. This way everything can be translated.
You can print the whole form with an echo of $oForm (goes through __toString()), but you have more control over the layout when you use specific widgetrender functions, like I do with renderRow(). This method takes the helptext as an argument, with is also translated.
The submit button is no widget, so we place it ourselves the old-fashioned way ... no helper, that is so Symfony 1.0.
That one is new. It is there, but we never defined it. It is created within sfForm and only since beta4 when indicated in settings.yml:
#Form security secret (CSRF protection)
csrf_secret: hierjeeigenc0d3 # Unique secret to enable CSRF protection or false to disable
You can choose your own code, on which the hash inside the CSRF value is based.
The form functionally is ready, but we want more control over the layout. I am a supporter of the tableless HTML design and the standard formatter of sfForm uses ... tables. Well, we can do better.
The form controller showed the coupling with my own formatter:
/* * Set decorator */ $oDecorator = new sfWidgetFormSchemaFormatterDiv($this->getWidgetSchema()); $this->getWidgetSchema()->addFormFormatter('div', $oDecorator); $this->getWidgetSchema()->setFormFormatterName('div');
I will now go into this part.
I have a class sfWidgetFormSchemaFormatterDiv in sfWidgetFormSchemaFormatterDiv.class.php made in the application-level lib/ directory so that all modules of can use it.
This takes care of the HTML layout of the form elements.
class sfWidgetFormSchemaFormatterDiv extends sfWidgetFormSchemaFormatter { protected $rowFormat = '%error%%field%<br />%help%<br />', $helpFormat = '<span class="help">%help%</span>', $errorRowFormat = '<div>%errors%</div>', $errorListFormatInARow = '%errors%', $errorRowFormatInARow = '<div class="formError">↓ %error% ↓</div>', $namedErrorRowFormatInARow = '%name%: %error%<br />', $decoratorFormat = '<div id="formContainer">%content%</div>'; }
A good article is available that describes this system.
For people that wonder why the label (%label% placeholder) is not used: $rowFormat sets the layout of the renderRow() method and since I want to render the label separately (i18n), it must not be rendered a second time by renderRow().
Hopefully the above can be a good help for your own form in Symfony 1.1. The documentation is quite scarce at the moment, so each bit of help will be welcome.
If the English is somewhat bad, I did a automatic translation of my original Dutch version of the article and tuned that a bit. The reason? I am lazy. ;-)
If you find errors in the above, it is because of copying my code probably. Please mention it in the comments.
Good luck!
Symfony 1.1 comes with a complete new form system. It works completely according to the MVC draft:
Make sure you have a running Symfony 1.1 based project and application and modules. In this example I build the form inside the myModule module and myLogin action.
My form makes use of i18n, which is in my case autoloaded in settings.yml.
This tutorial uses Symfony 1.1 beta4 and RC1. There are a little important changes with respect to beta3, which I don't cover.
I also expect you to have practical knowledge and a little bit experience with Symfony as system. I will not explain how you i18n implements or modules shield with security.yml.
The form gets two import fields: username and password. Furthermore is there a hidden field in which the URI comes that the user requested, but got redirected to the loginform (through Symfony’s security.yml and settings.yml). This will be used to go to that URI again after a successful login.
Both imput fields are required I will build a custom validation for a correct username/password check. Also we want to make use of a little new protection feature: CSRF.
The form takes uses i18n for multilinguity, I will use English primarily, but the view has been prepared for other languages.
We will begin with the action which contains the primary control.
/** * Executes myLogin action * * Login functionality. * * @param void * @return void * @access public */ public function executeMyLogin() { // Erase auth data $this->getUser()->clearCredentials(); $this->getUser()->setAuthenticated(FALSE); // Build login form $oForm = new inloggenForm(); if ($this->getRequest()->isMethod('post')) { // When called through POST (form submit) $oForm->bind( array('username' => $this->getRequest()->getParameter('username'), 'password' => $this->getRequest()->getParameter('password'), 'referrer' => $this->getRequest()->getParameter('referrer'), ) ); // Save orginal requested location in referrer field $oForm->setDefault('referrer', $this->getRequest()->getParameter('referrer')); if ($oForm->isValid()) { // When validations OK $aValues = $oForm->getValues(); sfContext::getInstance()->getLogger()->debug($aValues['username']); // Authentification $this->getUser()->setAuthenticated(TRUE); // To requested page $this->redirect($this->getRequest()->getParameter('referrer')); } } else { // Save original requested uri in form $oForm->setDefault('referrer', sfContext::getInstance()->getRequest()->getUri()); } $this->oForm = $oForm; // form to view }
Logic of authentification is set after POST further. Through the sfForm::bind() method couples the input of the user coupled with the form controller.
I made this in myModule/lib/form/inloggenForm.class.php. In the form is defined and coupled with the validations and the formatting.
<?php class inloggenForm extends sfForm { /** * Prepare validators */ private function _setValidators() { $this->oValGebruikersnaam = new sfValidatorAnd( array( new sfValidatorString(array('min_length' => 3, 'max_length' => 50), array('min_length' => 'The username should be at least three characters long', 'max_length' => 'The username should be fifty characters long at most', ) ), new sfValidatorCallback(array('callback' => array('cmsLoginValidator', 'execute'), 'arguments' => array() ), array('invalid' => 'This username/password combination is unknown') ), ), array('required' => TRUE), array('required' => 'The username is mandatory') ); $this->oValWachtwoord = new sfValidatorString(array('required' => TRUE), array('required' => 'The password is mandatory') ); $this->oValReferrer = new sfValidatorString(array('required' => FALSE)); } /** * Prepare widgets */ private function _setWidgets() { $this->oWidGebruikersnaam = new sfWidgetFormInput(array(), array('id' => 'username', 'size' => 25)); $this->oWidWachtwoord = new sfWidgetFormInputPassword(array(), array('id' => 'password', 'size' => 10)); $this->oWidReferrer = new sfWidgetFormInputHidden(array(), array('id' => 'referrer')); } /** * Configure form */ public function configure() { $this->_setValidators(); $this->_setWidgets(); /* * Set validators */ $this->setValidators(array('username' => $this->oValGebruikersnaam, 'password' => $this->oValWachtwoord, 'referrer' => $this->oValReferrer, ) ); /* * Set widgets */ $this->setWidgets(array('username' => $this->oWidGebruikersnaam, 'password' => $this->oWidWachtwoord, 'referrer' => $this->oWidReferrer, ) ); /* * Set decorator */ $oDecorator = new sfWidgetFormSchemaFormatterDiv($this->getWidgetSchema()); $this->getWidgetSchema()->addFormFormatter('div', $oDecorator); $this->getWidgetSchema()->setFormFormatterName('div'); $this->getWidgetSchema()->setHelps(array('username' => 'Please enter your username', 'password' => 'Please enter your password' ) ); } /** * Bind override */ public function bind(array $taintedValues = null, array $taintedFiles = array()) { $request = sfContext::getInstance()->getRequest(); if ($request->hasParameter(self::$CSRFFieldName)) { $taintedValues[self::$CSRFFieldName] = $request->getParameter(self::$CSRFFieldName); } parent::bind($taintedValues, $taintedFiles); } }
There are two private methods:
I overloaded the earlier mentioned bind() method to process the CSRF token internally. This field is regulated by sfForm internally, you to do need to worry about it much, only with the actual functionality.
The configure() method contains the functionality. The validators are created and linked to the corresponding fields and also are the widgets. Also, the decorator is defined with I will go into later on.
In _setValidators() sfValidatorBase objects are made for each field.
The password field check is the simplest, only the required input is checked. The object is of the type sfValidatorString (extend sfValidatorBase) without extra controls, only the required attribute with errortext is specified. In principle, you can use each validator as -empty- container.
The username is a combination; it is required, there are restrictions to the the stringlength and a correct login is checked. The stringcontrole/requirement is checked through sfValidatorString, which is quite simple.
The check for a correct login is done through a special validator, that does a callback to an custom function: sfValidatorCallback. This is explained later.
Since these two validators check the same field , the sfValidatorAnd validator is used that combines several validators. All validators must be satisfied. Of course Symfony also offers sfValidatorOr that checks that at least one underlying validator satisfies.
As you can see the callback validator calls to a custom class/method: myLoginValidator::execute().
/** * Fiel with myLoginValidator klasse * * @package - */ /** * Validation correct username/password * * @author Jordi Backx (Snowkrash) * @copyright Copyright © 2008, Jordi Backx (Snowkrash) * @package - */ class myLoginValidator { /** * execute validator * * @param sfValidatorBase Validator instance that calls this method * @param string Value of field that sfValidatorCallback checks * @param array Arguments for correct working * * @return value field when OK. Nothing if error (sfValidatorError exception) */ public static function execute ($oValidator, $sValue, $aArguments) { if ( /* check OK */ ) { // Return waarde veld indien controle OK return $sValue; } // Throw exception when not OK throw new sfValidatorError($oValidator, 'invalid', array('value' => $sValue, 'invalid' => $oValidator->getOption('invalid'))); } }
I set this here with no further logic, that is application specific, thus that you 'll have to do yourself. The base structure can be used. The three parameters must be defined, otherwise the whole application crashes.
In _setWidget() sfWidget objects are made for each field.
The widgets are the form elements: finally <input>, <select> etc tags in combination with labels and errortexts.
Each widget can have HTML attributes, which will be printed inside the form elements.
Finally the form must be printed to the screen through a view template.
<p><?php echo __('You need to log in to be able to use the Content Management System.') ?></p> <div id="formContainer"> <?php if ($oForm->getErrorSchema()->getErrors()) { ?> <div id="formulierFouten"> <ul> <?php foreach ($oForm->getErrorSchema() as $sError) { ?> <li><?php echo __($sError) ?></li> <?php } ?> </ul> </div> <?php } ?> <form action="<?php echo url_for('myModule/myLogin') ?>" method="post"> <?php echo $oForm['username']->renderLabel(__($oForm['username']->renderLabelName())); echo $oForm['username']->renderRow(__($oForm->getWidgetSchema()->getHelp('username'))); ?> <?php echo $oForm['password']->renderLabel(__($oForm['password']->renderLabelName())); echo $oForm['password']->renderRow(__($oForm->getWidgetSchema()->getHelp('password'))); ?> <?php echo $oForm['referrer']->render(array('value' => $oForm->getDefault('referrer'))) ?> <?php echo $oForm['_csrf_token'] ?> <label for="inloggen"> </label><input type="submit" value="Inloggen" id="inloggen" class="aanmeldenSubmit" /> </form> </div>
You can see all the i18n code (__() helper) and some non-Symfony 1.0 form building. Errorlists are built through the errorSchema which is available within the form object, the texts themself can be translated as you can see.
Also the labels and help texts are squeezed through i18n. The field names are in English, because the labels are based on these and must go through i18n. This way everything can be translated.
You can print the whole form with an echo of $oForm (goes through __toString()), but you have more control over the layout when you use specific widgetrender functions, like I do with renderRow(). This method takes the helptext as an argument, with is also translated.
The submit button is no widget, so we place it ourselves the old-fashioned way ... no helper, that is so Symfony 1.0.
That one is new. It is there, but we never defined it. It is created within sfForm gedefinieerd and only (since beta4) when indicated in settings.yml:
#Form security secret (CSRF protection)
csrf_secret: hierjeeigenc0d3 # Unique secret to enable CSRF protection or false to disable
You can choose your own code, on which the hash inside the CSRF value is based.
The form functionally ready, but we want more control over the layout. I am a supporter of the tableless HTML design and the standard formatter of sfForm uses ... tables. Well, we can do better.
The form controller showed the coupling with my own formatter:
/* * Set decorator */ $oDecorator = new sfWidgetFormSchemaFormatterDiv($this->getWidgetSchema()); $this->getWidgetSchema()->addFormFormatter('div', $oDecorator); $this->getWidgetSchema()->setFormFormatterName('div');
I will now go into this part.
I have a class sfWidgetFormSchemaFormatterDiv in sfWidgetFormSchemaFormatterDiv.class.php made in the application-level lib/ directory so that all modules of can use it.
This takes care of the HTML layout of the form elements.
class sfWidgetFormSchemaFormatterDiv extends sfWidgetFormSchemaFormatter { protected $rowFormat = '%error%%field%<br />%help%<br />', $helpFormat = '<span class="help">%help%</span>', $errorRowFormat = '<div>%errors%</div>', $errorListFormatInARow = '%errors%', $errorRowFormatInARow = '<div class="formError">↓ %error% ↓</div>', $namedErrorRowFormatInARow = '%name%: %error%<br />', $decoratorFormat = '<div id="formContainer">%content%</div>'; }
A good article is available that describes this system.
For people that wonder why the label (%label% placeholder) is not used: $rowFormat sets the layout of the renderRow() method and since I want to render the label separately (i18n), it must not be rendered a second time by renderRow().
Hopefully the above can be a good help for your own form in Symfony 1.1. The documentation is quite scarce at the moment, so each bit of help will be welcome.
If the English is somewhat bad, I did a automatic translation of my original Dutch version of the article and tuned that a bit. The reason? I am lazy. ;-)
If you find errors in the above, it is because of copying my code probably. Please mention it in the comments.
Goog luck!
A Latitude Longitude validator that allows you to specify very exact constraints for the co-ordinates that are submitted.
<?php /* * This file is part of the symfony package. * (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * myLatLngValidator * * @description This class validator will validate the entered latitude and * longitudes submitted using a form or other method. * @subpackage validator * @author Nathan Rzepecki * @created 21/4/2008 */ class myLatLngValidator extends sfValidator { /** * Executes this validator. * * @param mixed A file or parameter value/array * @param error An error message reference * * @return bool true, if this validator executes successfully, otherwise false */ public function execute(&$value, &$error) { // // echo '<pre>value is: '.$value.'</pre>'; // echo '<pre>min_type: '.$this->getParameterHolder()->get('min_type').'</pre>'; // echo '<pre>max type: '.$this->getParameterHolder()->get('max_type').'</pre>'; // echo '<pre>min: '.$this->getParameterHolder()->get('min').'</pre>'; // echo '<pre>max: '.$this->getParameterHolder()->get('max').'</pre>'; // exit; // echo '<pre>value: '.$value.'</pre>'; // echo '<pre>max type: '.$this->getParameterHolder()->get('max_type').'</pre>'; // echo '<pre>min type: '.$this->getParameterHolder()->get('min_type').'</pre>'; // echo '<pre>min: '.$this->getParameterHolder()->get('min').'</pre>'; // echo '<pre>max: '.$this->getParameterHolder()->get('max').'</pre>'; // echo '<pre>'..'</pre>'; /* * If the min_type was set */ if ($this->getParameterHolder()->get('min_type') == '+') { // type was positive $re = '/^\d{1,3}(\.(\d*)){0,1}$/'; if (!preg_match($re, $value)) { $error = $this->getParameterHolder()->get('min_type_error'); return false; } // end if } elseif ($this->getParameterHolder()->get('min_type') == '-') { // type was negative $re = '/^-\d{1,3}(\.(\d*)){0,1}$/'; if (!preg_match($re, $value)) { $error = $this->getParameterHolder()->get('min_type_error'); return false; } // end if } else { // don't care if it is plus or minus $re = '/^-{0,1}\d{1,3}(\.(\d*)){0,1}$/'; if (!preg_match($re, $value)) { $error = $this->getParameterHolder()->get('min_type_error'); return false; } // end if } // end if elseif else /* * if max_type was set */ if ($this->getParameterHolder()->get('max_type') == '+') { // type was positive $re = '/^\d{1,3}(\.(\d*)){0,1}$/'; if (!preg_match($re, $value)) { $error = $this->getParameterHolder()->get('max_type_error'); return false; } // end if } elseif ($this->getParameterHolder()->get('max_type') == '-') { // type was negative $re = '/^-\d{1,3}\.{0,1}\d+$/'; // negative digit if (!preg_match($re, $value)) { $error = $this->getParameterHolder()->get('max_type_error'); return false; } // end if } else { // don't care if it is plus or minus $re = '/^-{0,1}\d{1,3}(\.(\d*)){0,1}$/'; if (!preg_match($re, $value)) { $error = $this->getParameterHolder()->get('max_type_error'); return false; } // end if } // end if elseif else /* * if max value was set */ if ($this->getParameterHolder()->get('max')) { $re = '/^-\d{1,3}(\.(\d*)){0,1}$/'; // negative digit if (preg_match($re, $this->getParameterHolder()->get('max'))) { // yes its a negative so remove the prefix - $maxValue = substr($this->getParameterHolder()->get('max'), 1); if (!preg_match($re, $value)) { $error = $this->getParameterHolder()->get('max_type_error'); return false; } else { // both the max value and the value are negative so test that the value is less than the max value if (!($maxValue > substr($value, 1))) { $error = $this->getParameterHolder()->get('max_error'); return false; } // end if } // end if else } else { $maxValue = $this->getParameterHolder()->get('max'); $re = '/^\d{1,3}(\.(\d*)){0,1}$/'; // positive digit if (preg_match($re, $value)) { // Yeah the value is a positive so make sure its within range if (!($maxValue > $value)) { $error = $this->getParameterHolder()->get('max_error'); return false; } // end uf } else { $error = $this->getParameterHolder()->get('max_type_error'); return false; } // end if else positive }// end if } // end if /* * if min value was set */ if ($this->getParameterHolder()->get('min')) { $re = '/^-\d{1,3}(\.(\d*)){0,1}$/'; // negative digit if (preg_match($re, $this->getParameterHolder()->get('min'))) { // yes its a negative so remove the prefix - $minValue = substr($this->getParameterHolder()->get('min'), 1); if (!preg_match($re, $value)) { // the min value was negative so the value should be nexative. This is not so error it $error = $this->getParameterHolder()->get('min_type_error'); return false; } else { // both the max value and the value are negative so test that the value is less than the max value if (!(substr($value, 1) > $minValue)) { $error = $this->getParameterHolder()->get('min_error'); return false; } // end if } // end if else } else { $minValue = $this->getParameterHolder()->get('min'); $re = '/^\d{1,3}(\.(\d*)){0,1}$/'; // positive digit if (preg_match($re, $value)) { // Yeah the value is a positive so make sure its within range if (!($value > $minValue)) { $error = $this->getParameterHolder()->get('min_error'); return false; } // end if } else { $error = $this->getParameterHolder()->get('min_type_error'); return false; } // end if else positive }// end if } // end if // was not returned out of any of the above so must be good return true; } /** * Initializes this validator. * * @param sfContext The current application context * @param array An associative array of initialization parameters * * @return bool true, if initialization completes successfully, otherwise false */ public function initialize($context, $parameters = null) { // initialize parent parent::initialize($context, $parameters); // set defaults $this->getParameterHolder()->set('max', null); $this->getParameterHolder()->set('max_error', 'The lat / lng is not within range'); $this->getParameterHolder()->set('max_type', null); $this->getParameterHolder()->set('max_type_error', 'Your lat / lng did not match the specified type'); $this->getParameterHolder()->set('min', null); $this->getParameterHolder()->set('min_error', 'The lat / lng is not within range'); $this->getParameterHolder()->set('min_type', null); $this->getParameterHolder()->set('min_type_error', 'Your lat / lng did not match the specified type'); //$this->getParameterHolder()->set('', null); $this->getParameterHolder()->add($parameters); return true; }// end function } // end class myLatLngValidator
You use it like so.
latitude:
required:
msg: Please enter the latitude or position the marker where your farm is
myLatLngValidator:
min: -9
min_error: Your entered latitude is not within min range
min_type: '-'
min_type_error: Your latitude should be in the negative range
max: -45
max_error: Your entered latitude is not within max range
max_type: '-'
max_type_error: Your latitude should be in the negative range
longitude:
required:
msg: Please enter the longitude or position the marker where your farm is
myLatLngValidator:
min: 111
min_error: Your longitude is not within min range
min_type: '+'
min_type_error: Your longitude should be in the positive range
max: 154
max_error: Your longitude is not within max range
max_type: '+'
max_type_error: Your longitude should be in the positive range
I may clean it up in the future. This was so I could constrain the points to be within Australia.
This images validations is an extention for the sfFileValidator. You can use it for validate uploaded images maximum width and height, minimum width and height and if the images have square dimensions.
<?php /** * sfFileImageValidator allows you to apply constraints to image file upload, it extend the sfFileValidator functions. * * <b>Optional parameters:</b> * * # <b>max_height</b> - [none] - Maximum images height in pixels. * # <b>max_height_error</b> - [The file height is too large] - An error message to use when * images height is too large. * # <b>max_width</b> - [none] - Maximum images width in pixels. * # <b>max_width_error</b> - [The file width is too large] - An error message to use when * images width is too large. * # <b>min_height</b> - [none] - Minimum images height in pixels. * # <b>min_height_error</b> - [The file height is too small] - An error message to use when * images height is too small. * # <b>min_width</b> - [none] - Minimum images width in pixels. * # <b>min_width_error</b> - [The file width is too small] - An error message to use when * images width is too small. * # <b>is_square</b> - [false] - The image is a square * # <b>is_square_error</b> - [The file is not a square] - An error message to use when * the images is not a square * (The width size is not equal * to the height size). * @package symfony * @subpackage validator * @author Daniel Santiago */ class sfFileImageValidator extends sfFileValidator { /** * Executes this validator. * * @param mixed A file or parameter value/array * @param error An error message reference * * @return bool true, if this validator executes successfully, otherwise false */ public function execute(&$value, &$error) { if (parent::execute($value, $error)) { list($width, $height) = @getimagesize($value['tmp_name']); // File is not a square $is_square = $this->getParameter('is_square'); if ($is_square && $width != $height) { $error = $this->getParameter('is_square_error'); return false; } // File height too large $max_height = $this->getParameter('max_height'); if ($max_height !== null && $max_height < $height) { $error = $this->getParameter('max_height_error'); return false; } // File width too large $max_width = $this->getParameter('max_width'); if ($max_width !== null && $max_width < $width) { $error = $this->getParameter('max_width_error'); return false; } // File height too small $min_height = $this->getParameter('min_height'); if ($min_height !== null && $min_height > $height) { $error = $this->getParameter('min_height_error'); return false; } // File width too small $min_width = $this->getParameter('min_width'); if ($min_width !== null && $min_width > $width) { $error = $this->getParameter('min_width_error'); return false; } return true; } } /** * Initializes this validator. * * @param sfContext The current application context * @param array An associative array of initialization parameters * * @return bool true, if initialization completes successfully, otherwise false */ public function initialize($context, $parameters = null) { // initialize parent parent::initialize($context, $parameters); // set defaults $this->getParameterHolder()->set('max_height', null); $this->getParameterHolder()->set('max_height_error', 'The file height is too large'); $this->getParameterHolder()->set('max_width', null); $this->getParameterHolder()->set('max_width_error', 'The file width is too large'); $this->getParameterHolder()->set('min_height', null); $this->getParameterHolder()->set('min_height_error', 'The file height is too small'); $this->getParameterHolder()->set('min_width', null); $this->getParameterHolder()->set('min_width_error', 'The file width is too small'); $this->getParameterHolder()->set('is_square', false); $this->getParameterHolder()->set('is_square_error', 'The file is not a square'); $this->getParameterHolder()->add($parameters); return true; } }
In the YAML validation file put this:
news{photo}: file: yes sfFileImageValidator: min_height: 100 min_height_error: 'The image height is too small, it must have minimum 100px' min_width: 120 min_width_error: 'The image width is too small, it must have minimum 120px' max_height: 960 max_height_error: 'The image height is too large, it must have maximum 960px' max_width: 450 max_width_error: 'The image width is too large, it must have maximum 450px' is_square: true is_square_error: 'The images must be a square (The height be equal to the width)' max_size: 256000 max_size_error: 'The maximum images size is 250Kb' mime_types_error: 'We only accept GIF, PNG and JPEG.' mime_types: - 'image/jpeg' - 'image/png' - 'image/gif'
This its a password strength validator, with ajax request for checking the password field.
First create a validator in lib/validators/sfPasswordStrengthValidator.class.php
<?php class sfPasswordStrengthValidator extends sfValidator { public function execute (&$value, &$error) { $weakness = $this->Password_Strength($value); if($weakness==1) { $error = $this->getParameter('strength_error'); return false; } return $weakness; } public function initialize ($context,