XF 2.0 handling username changes in addon

AndrewSimm

Well-known member
How can I link am username field in an addon to username change in XF? They share a relation in the entity via user_id.
 
You'll want to hook into the user_content_change_init and/or user_delete_clean_init events in any add-on which has tables with user_id and/or username columns. The former is for handling user ID and username changes that occur due to user renames, merges, and deletions. It will update the rows with the new username or user ID, but will not delete rows when a user is deleted. The latter is for deleting rows when a user is deleted, in which case you'll want to set emptyable to false for that table in the former event.

For the former, consider posts, which are updated accordingly but not removed when a user is deleted. In user_content_change_init:
PHP:
$updates['xf_post'] = ['user_id', 'username'];


For the latter, consider poll votes, which are removed when a user is deleted. In user_content_change_init:
PHP:
$updates['xf_poll_vote'] = ['user_id', 'emptyable' => false];
... and in user_delete_clean_init:
PHP:
$deletes['xf_poll_vote'] = 'user_id = ?';

Setting emptyable to false ensures the user_id is not set to 0 on deletion, so that the rows can be deleted accordingly.

Lastly, there is user_merge_combine, which is for situations where you need to combine the data of two users when they are merged. For example, message counts are combined when users are merged:
PHP:
$target->message_count += $source->message_count;
 
Last edited:
Back
Top Bottom