In my model, let's call it "questions", I have "active" field (TINYINT). The idea is, that only one entry in that particular model can be active. So when I update one entry by checking "active" checkbox, this entry should turn into active, and the other one should turn into unactive (I mean that one which has been active before). Any idea what query should I use?
Asked
Active
Viewed 242 times
0
-
I answered a similar question here: http://stackoverflow.com/questions/11259394/cakephp-one-column-one-true/11259976#11259976 – RichardAtHome Aug 30 '12 at 13:25
2 Answers
2
some kind of toggle behavior for example.
this behavior you write makes the model $actsAs = array('Toggable', array('field'=>'active'));
and in your afterSave hook you make an updateAll call to reset all active ones to inactive (except the current id of course)
that would be the cleanest approach. of course, you can always make a quick-and-dirty one using the models hooks itself for this.

mark
- 21,691
- 3
- 49
- 71
-
PS: here is an old version which does sth similar: http://josediazgonzalez.com/2009/08/13/toggle-behavior/ (but you should probably make your own 2.x one - just for some basic behavior guidelines) – mark Aug 30 '12 at 13:20
0
I don't know how to do that. It's little above my current knowledge :)
This is how I figured it out so far:
function admin_edit($id = null) {
$this->Question->id = $id;
if (empty($this->data)) {
$this->data = $this->Question->read();
} else {
if ($this->Question->save($this->data)) {
$active = $this->data['Question']['active'];
$total = $this->Question->find('count');
$i=1;
if ($i == '1') {
while($active <= $total){
$this->Question->query("UPDATE questions SET active = '0'");
$i++;
}
$this->Question->query("UPDATE questions SET active = '1' WHERE id = '$id'");
}
$this->redirect(array('action' => 'index'));
}
}
And it's working but I guess it's not the "cleanest approach". Any tips how to simplify it thereafter?

danny3b
- 313
- 5
- 17