2

I'm trying to run a quick check to see if any of my user's data has changed before saving them. However, I'm running into a situation where I can only access the new data.

I can't tell if this is a bug, or simply a misunderstanding of how it works...

craft()->on('users.beforeSaveUser', function(Event $event) {

    // Only do this for existing users
    if(!$event->params['isNewUser'])
    {

        // Get ID of user about to be saved
        $userId = $event->params['user']->id;

        // Look up existing user data
        $existing = craft()->users->getUserById($userId);

        // Why does this contain the NEW data?
        Craft::dd($existing->myField);

    }

});

There may be a reasonable explanation as to why the pre-existing user data is not available. If that is the case, then how can I access the pre-existing data for this user?

3

Not totally sure, but I believe this may be because the UsersService actually caches UserModels fetched by getUserById() locally in a private class variable.

Instead of using getUserById(), try pulling the user with an ElementCriteriaModel:

$existing = craft()->elements->getCriteria(ElementType::User, array(
    'id' => $userId,
))->first();
  • 3
    Yeah, there's some memoization of the new data going on before that event is fired is the problem. – Brad Bell Jun 21 '16 at 20:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.