Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

afterFetch() find() doesn't work?

I use afterFetch() it's doesn't work when find() , it's only used in findFirst() how to do this?



635
Accepted
answer

Could you explain what it is exactly you would like to do with the data in afterFetch()?
As I'm sure you know, the Model events like afterFetch() are called on Model instances, so the easiest way to access the events would just be to loop over the ResultSet:

$models = Model::find();  
foreach ($models as $model) {  
  do something // afterFetch() is called on each Model instance before whatever you do here  
}

Could you explain a little more please?



12.9k

thanks for your reply, and in my model Users where have a field named 'audit' and it's value is Int (1,2,3....). But in my view(volt) I will show it as 1-Approve,2-Unapprove,3-commit.... so there will many description and I will change it sometime. so I dont want to define it in view, I want to define it in model so when I find a model it outo change as description as CI do.

I see... ok thanks for explaining. It might help people in a similar situation.
In that case, when you loop through the users in your view with volt's {% for user in users %}, the afterFetch() will be called naturally on each iteration.
However, instead of using afterFetch(), I might suggest something like the following in your case. That way, you can leave the model untouched and not worry about changing the values back/altering the dirty state.

// model
public function getAuditName()
{
    switch ($this->audit) {
        case '1':
            return 'Approve';
            break;
        case '2':
            return 'Unapprove';
            break;
        case '3':
            return 'commit';
            break;
        etc....
    }
}

// view
{% for user in users %}
  {{ user.getAuditName() }}
{% endfor %}

thanks for your reply, and in my model Users where have a field named 'audit' and it's value is Int (1,2,3....). But in my view(volt) I will show it as 1-Approve,2-Unapprove,3-commit.... so there will many description and I will change it sometime. so I dont want to define it in view, I want to define it in model so when I find a model it outo change as description as CI do.