tags:

views:

305

answers:

2

I'm using the following widget to allow a user to input a date

$this->widgetSchema['first_registration'] = new sfWidgetFormDate(array(
  'format' => '%month%/%year%',
  'years' => range(date('Y', time()) - 15, date('Y', time()) + 15)
));

The default format for a date using this widget is %month%/%day%/%year% and so that's what the default validator for this widget checks for. However, I've attempted to alter the validator...

$this->validatorSchema['first_registration'] = new sfValidatorDate(array(
  'date_format' => '%month%/%year%',
  'with_time' => false
));

This isn't working and I'm still getting an invalid error. Does anybody know why?

+2  A: 

Your widget and validator still include the day field.

All your format argument does is to prevent the day from displaying - it still exists and is being validated behind the scenes. I expect that this is where the problem is occurring.

I'd recommend the easiest fix is to default the day to 1 by over-riding the bind method on the form in question. Not sure how you are doing things, but when I am working with month/year dates I often do this in the database, as it allows native date/time formats to work correctly - same argument applies to symfony forms.

// untested code - i may have array structure/method signatures incorrect.
function bind($taintedValues = array(), $taintedFiles = array()) {
  $taintedValues['first_registration']['day'] = 1;
  return parent::bind($taintedValues, $taintedFiles);
}

Additionally, the date_format option for sfValidatorDate takes a regular expression as its argument, not a format as used in sfWidgetFormDate.

benlumley
Thanks, got it working!
aaronfalloon
Cool - glad to help! :)
benlumley
A: 

I'm having exactly the same problem and I stumbled upon this answer

I just have a question... where do I put this code?

Thank you very much for your help!

EDIT:

I suppose it's to override the bind method from the sfForm. Am I right?

Also would this work while still hiding the day from the form?

petersaints