Mark required field in a Symfony Form (sfForm) with an asterisk

How to mark required / mandatories fields in a form based on sfForm ? (solution based on Dark-IT post, adapted and tested on Symfony 1.2)
Add in your lib/form directory a class name : RegistrationForm.php (you can name it as you want of course)

class RegistrationForm extends sfForm
{
public function configure()
{
// …
}

public function render($attributes = array())
{
$formatterObj = $this->widgetSchema->getFormFormatter();
if(!is_null($formatterObj)) {
$formatterObj->setValidatorSchema($this->getValidatorSchema());
}
return parent::render($attributes);
}

public function __toString()
{
try
{
return $this->renderUsing(‘Registration’);
}
catch (Exception $e)
{
self::setToStringException($e);
// we return a simple Exception message in case the form framework is used out of symfony.
return ‘Exception: ‘.$e->getMessage();
}
}
}

Add another class in your lib/form directory : sfWidgetFormSchemaFormatterRegistration.php

class sfWidgetFormSchemaFormatterRegistration extends sfWidgetFormSchemaFormatter
{
protected
$rowFormat = “\n

%label% %error%%field%%help%%hidden_fields%”,
$requiredTemplate= ‘

*’,
$validatorSchema = null;/**
* Generates the label name for the given field name.
*
* @paramĀ  string $nameĀ  The field name
* @return string The label name
*/
public function generateLabelName($name)
{
$label = parent::generateLabelName($name);

$fields = $this->validatorSchema->getFields();
if($fields[$name] != null) {
$field = $fields[$name];
if($field->hasOption(‘required’) && $field->getOption(‘required’)) {
$label .= $this->requiredTemplate;
}
}

return $label;

}

public function setValidatorSchema(sfValidatorSchema $validatorSchema)
{
$this->validatorSchema = $validatorSchema;
}
}

Now, you can use this extended form in your form. Simply change the extends directive with :

class MyGreatForm extends RegistrationForm
{
// …
}

Of course, you have to update your css, for example :

.requiredFormField
{
color: red;
}

Leave a Reply

Your email address will not be published. Required fields are marked *