views:

75

answers:

1

Greetings,

In my view I have a date input, set like so:

echo $form->input('cc_expdate', array('label' => __('exp. date', true),
        'type' => 'date', 'dateFormat' => 'MY', 'default' => date('Y'),
        'minYear' => date('Y'), 'maxYear' => date('Y', strtotime("+10 years")),
        'orderYear' => 'asc', 'separator' => ' ', 'monthNames' => false));

And in my model I have a validation rule, viz:

'cc_expdate' => array(
    'rule' => array('date', 'my'),
 'message' => 'Please select a valid expiration date'
)

But the validation always fails. When I look at $this->data, I see that the date is being passed through the form as an array (e.g. 'cc_expdate' => array('month' => '10', 'year' => '2010')) but it seems the date validation rule expects a string like 10-2010. I hunted around Cake and checked the documentation but could find nothing covering this. It seems this should be a simple task to handle, am I missing something simple or does Cake not have a built in validation for 'date' form elements?

cheers,
-Bri

A: 

I had the same problem in a controller method recently where I was trying to save a month/year value into a MySQL date field and validation kept failing. I was using my/MY in the model/view for the date settings and it was passing the year and month as expected to $this->data when I checked it in the controller.

What I did was to set the day key to "1" in the date array passed from the form before validation in the controller, and then validation worked. This resulted in all my month/year dates being stored as the 1st of the month, which was fine for my app.

I'm still new to CakePHP, so this might be considered a hack, I'm not sure. My date field in the database was a MySQL date field, so I was wondering if maybe it was failing validation for some reason due to the day being missing (maybe using varchar would save the month/year as a string?).

whelanska
@whelanska - I tried this suggestion but still the validation would fail. I went ahead and stepped through the code in `validation.php` and `model.php` and found that date values start as an array and are converted into a mysql safe string in `model.php`. Of course, this format is YYYY-MM-DD, which fails when passed to the "my" validation rule. Changing the validation rule to "ymd" validates properly. This seems rather silly; it's like the date rule with anything other than "ymd" is for strings only, unless you convert your date arrays yourself or use a custom rule.
saturn_rising
And thanks for the tip, it saves me from having to convert my db field to varchar.
saturn_rising