开发者

Symfony Form: Set default/value on error?

开发者 https://www.devze.com 2023-02-09 01:07 出处:网络
My crazy designer would like the message \"Required\" displaying (in red) inside 开发者_C百科a field if the form has been submitted and it is invalid because of an empty field.

My crazy designer would like the message "Required" displaying (in red) inside 开发者_C百科a field if the form has been submitted and it is invalid because of an empty field.

The form in question is a login prompt and I'm using a custom class that extends sfGuardFormSignin

I've managed to set the value and add a class with..

$this->widgetSchema['username']->setAttribute('class','red');
$this->widgetSchema['username']->setDefault('Required');

..but how do I do this only when the username field is invalid and because of the Required error?

I assume it's the same for the password field?

Many thanks in advance

EDIT:

Thanks for the advice greg0ire. I've had a play with that but the formatRow method of sfWidgetFormSchemaFormatter doesn't seem to be getting hit. Is this because my form extends sfGuardFormSignin and using the sfGuardAuth plugin?

class FrontendsfGuardFormSignin extends sfGuardFormSignin
{
  public function configure()
  {
    parent::configure();

    // This works!
    $this->widgetSchema['username']->setLabel('Email');

    // I copied this from the link you pasted
    $decorator = new myWidgetFormSchemaFormatterCustom($this->getWidgetSchema());
    $this->widgetSchema->addFormFormatter('custom', $decorator);
    $this->widgetSchema->setFormFormatterName('custom');
  }
}

/lib/widget/myWidgetFormSchemaFormatterCustom.class.php

class myWidgetFormSchemaFormatterCustom extends sfWidgetFormSchemaFormatter
{

  public function __construct(sfWidgetFormSchema $widgetSchema)
  {
    parent::__construct($widgetSchema);
  }

  public function formatRow($label, $field, $errors = array(), $help = '', $hiddenFields = null)
  {
    // Nothing happens!?
    var_dump($errors);
    die();
    parent::formatRow($label, $field, $errors, $help, $hiddenFields);
  }

}


$widget->render(array('value' => $widget->getError()));


Designers have such crazy ideas...

You'll have to write a custom schema formatter to do this. You'll probably have to override the formatRow() method to achieve this.

Analyse the $errors array argument of this method, and if you spot the "Required" error in it, then do your special stuff. You won't need to use the code you posted in your question.

0

精彩评论

暂无评论...
验证码 换一张
取 消