Domanda

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.

È stato utile?

Soluzione

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';
    }
}

Altri suggerimenti

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

$this->data[$this->alias]['status'] = $this->status();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top