Wednesday, May 27, 2009

Re: using invalidate

Ok, although I'm not satisfied with Model::save() saving the non
validating data, I've found a work-around.
It seems to work quite nice for me so why not posting it here:

Practically, what I'm trying to do is submitting agenda items through
a form. The items have a date, whole_day (bool), start and stop time.
I want the start and stop time to be required if the whole_day box is
not marked.

This is what I did initially:
The Item model doesn't have validation rules for start and stop. The
items controller checks if whole_day == false (meaning that start and
stop time would be required). In that case, start and stop is manually
validated and then decided weather or not to 'invalidate' those
fields. Quite a hassle...

Now, I'm doing the opposite: The model is setup to do validation on
all the fields. In the items controller, some validation rules are
removed depending on certain submitted values. To do the opposite of
invalidate, i've written a small model function named 'uninvalidate
()' ;-). Uninvalidate removes the validation rule for a given field.

/app/app_model.php

class AppModel extends Model
{
function uninvalidate($field)
{
if (isset($this->validate[$field])) {
unset($this->validate[$field]);
}
}
}

Validation rules in the Item model:

var $validate = array(
'start_time' => array('notempty'),
'stop_time' => array('notempty')
);

Now, the items controller logic looks like:

if ($this->data['Item']['whole_day'] == 1) {
$this->Item->uninvalidate('start_time');
$this->Item->uninvalidate('stop_time')
}

if ($this->Item->validates() && $this->Item->save($this->data)) {

}

Unlike my initial attempt, you leave the validation work to cake.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to cake-php+unsubscribe@googlegroups.com
For more options, visit this group at http://groups.google.com/group/cake-php?hl=en
-~----------~----~----~----~------~----~------~--~---

No comments: