Reputation: 856
I want to change the background color of my field when an error occurs.
In Java Struts, I can do something like this:
<s:textfield name="parameter" cssClass="normal_css_class" cssErrorClass="class_on_error" cssErrorStyle="style_on error"/>
I want to be able to perform something like above. The tag renders the field cssErrorClass when the field parameter has errors. No more additional Javascript is required.
Currently I have the following (very dirty) code in my template:
<?php if($form['bill_to']->hasError()): ?>
<?php echo $form['bill_to']->render(array('style' => 'background-color: red')) ?>
<?php else: ?>
<?php echo $form['bill_to']->render() ?>
<?php endif; ?>
<?php echo $form['bill_to']->renderError() ?>
The above code works but is there a way to implement it so that I just have to call:
<?php echo $form['bill_to']->render() ?>
and it will then perform the setting of the styles? I'm thinking of overriding the render() method but I am not sure if it is the right approach.
Upvotes: 0
Views: 1521
Reputation: 2893
You can extend the sfWidgetFormSchemaFormatter class like this:
class sfWidgetFormSchemaFormatterCustom extends sfWidgetFormSchemaFormatter
{
protected
$rowFormat = "<div class=\"%row_class%\">%label% %field% %hidden_fields% %help%</div>",
$helpFormat = "%help%",
$errorRowFormat = "",
$errorListFormatInARow = "\n%errors%\n",
$errorRowFormatInARow = "<span class=\"error\">%error%</span>\n",
$namedErrorRowFormatInARow = "%error%\n",
$decoratorFormat = "%content%";
public function formatRow($label, $field, $errors = array(), $help = '', $hiddenFields = null)
{
$row = parent::formatRow(
$label,
$field,
$errors,
$help,
$hiddenFields
);
return strtr($row, array(
'%row_class%' => (count($errors) > 0) ? ' error' : '',
));
}
}// decorator class
and apply it to a form inside it's configure() method like this:
class myForm extends sfForm
{
public function configure()
{
// ....
$formatter = new sfWidgetFormSchemaFormatterCustom($this->widgetSchema);
$this->widgetSchema->addFormFormatter('custom', $formatter);
$this->widgetSchema->setFormFormatterName('custom');
}
}
Upvotes: 2
Reputation: 1077
You may want to look into form formatters, see http://www.symfony-project.org/api/1_4/sfWidgetFormSchemaFormatter.
A formformatter object can be obtained with $this->getWidgetSchema()->getFormFormatter()
when you are in the configure method of your sfForm.
Upvotes: 0