Skip to content

Instantly share code, notes, and snippets.

@kriswallsmith
Created July 18, 2009 07:32
Show Gist options
  • Save kriswallsmith/149461 to your computer and use it in GitHub Desktop.
Save kriswallsmith/149461 to your computer and use it in GitHub Desktop.
<?php
class BaseDoctrineForm extends sfFormDoctrine
{
public function __construct($object = null, $options = array(), $CSRFSecret = null)
{
parent::__construct($object, $options, $CSRFSecret);
// tell the widget schema which fields are required
$this->widgetSchema->addOption('required_fields', $this->getRequiredFields());
$this->widgetSchema->addFormFormatter('table', new RequiredLabelsFormatterTable($this->widgetSchema));
}
protected function getRequiredFields(sfValidatorSchema $validatorSchema = null, $format = null)
{
if (is_null($validatorSchema))
{
$validatorSchema = $this->validatorSchema;
}
if (is_null($format))
{
$format = $this->widgetSchema->getNameFormat();
}
$fields = array();
foreach ($validatorSchema->getFields() as $name => $validator)
{
$field = sprintf($format, $name);
if ($validator instanceof sfValidatorSchema)
{
// recur
$fields = array_merge($fields, $this->getRequiredFields($validator, $field.'[%s]'));
}
else if ($validator->getOption('required'))
{
// this field is required
$fields[] = $field;
}
}
return $fields;
}
}
<?php
class RequiredLabelsFormatterTable extends sfWidgetFormSchemaFormatterTable
{
protected
$requiredLabelClass = 'required';
public function generateLabel($name, $attributes = array())
{
// loop up to find the "required_fields" option
$widget = $this->widgetSchema;
do
{
$requiredFields = (array) $widget->getOption('required_fields');
}
while ($widget = $widget->getParent());
// add a class (non-destructively) if the field is required
if (in_array($this->widgetSchema->generateName($name), $requiredFields))
{
$attributes['class'] = isset($attributes['class']) ?
$attributes['class'].' '.$this->requiredLabelClass :
$this->requiredLabelClass;
}
return parent::generateName($name, $attributes);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment