0

I'm trying to set a field on the fly inside a model, so it will get returned in my with any read action. I looked into virtual fields, but they're not quite right, since they basically execute SQL queries.

In this example, I'm trying to return a value, based on a simple check, to see whether or not a user has activated their account or not. Inside my model, I want to run this function:

public function status() {
    if ($this->field('password')) {
        return = 'active';
    } else if ($this->Ticket->field('id')) {
        return = 'pending';
    } else {
        return = 'inactive';
    }
}

The intent is to access that in my view via $user['User']['status'], so I could apply CSS styles, etc, based on the result.

But that in between of setting $this['User']['status'] = status() is eluding me right now.

Also, since I'm reading my list of Users different ways (sometimes with pagination, or one user at a time) this isn't something I want to set in my controller. I want the property to simply appear in the model when read.

Benjamin Allison
  • 2,076
  • 3
  • 29
  • 52

2 Answers2

2

How about doing your logic and appending it to the results in the afterFind callback? (which - per it's name is triggered after you do a find()) Something like this:

//User model
public function afterFind($results) {

    if ($this->field('password')) {
        $results[$this->alias]['status'] = 'active';

    } else if ($this->Ticket->field('id')) {
        $results[$this->alias]['status'] = 'pending';

    } else {
        $results[$this->alias]['status'] = 'inactive';
    }
}
Dave
  • 27,341
  • 18
  • 106
  • 177
  • Hmm... for some reason this gives me an error: Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 523800 bytes) – Benjamin Allison May 02 '12 at 14:39
  • 1
    Sounds like you have recursive set too high. I recommend setting `public $recursive = -1;` in your AppModel, then changing it only when you NEED it higher (though I don't think using recursive is a good idea - should be using Containable instead) – Dave May 02 '12 at 14:51
0

Try this in your callback where you want to call the status function:

$this->data[$this->alias]['status'] = $this->status();
Scott Harwell
  • 7,327
  • 2
  • 26
  • 41