简体   繁体   中英

Symfony Form: Set default/value on error?

My crazy designer would like the message "Required" displaying (in red) inside 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM