#StackBounty: #7 #users #hooks Modified user record during presave hook not saving properly

Bounty: 50

A project I am working on has a bug where an array field on the user object is getting duplicated values. To fix this bug, I am implementing the hook_user_presave hook in one of our custom modules to strip out any duplicated values in the array before saving. Essentially, here is my code:

function my_module_user_presave(&$edit, $account, $category) {
    watchdog('ARRAY BEFORE MODIFICATION', '<pre>' . print_r($edit['field_some_array'], true) . '</pre>');
    $array_field = $edit['field_some_array']['und'];
    $new_array_field = [];
    for ($i = 0; $i < count($array_field); $i++) {
        $item_exists = false;
        for ($j = 0; $j < count($new_array_field); $j++) {
            if ($array_field[$i]['target_id'] == $new_array_field[$j]['target_id']) {
                $item_exists = true;
        if (!$item_exists) {
            array_push($new_array_field, $array_field[$i]);
    $edit['field_some_array']['und'] = $new_array_field;
    watchdog('ARRAY AFTER MODIFICATION', '<pre>' . print_r($edit['field_some_array'], true) . '</pre>');

You notice that there is two watchdogs, and I can confirm that when these are printed out they show the expected results: $edit[field_some_array] has duplicates in the first watchdog log and then does not have duplicates in the second watchdog log.

However, when this actually saves, the duplicate values still exist…

In Drupal’s own documentation it specifically states: $edit: The array of form values submitted by the user. Assign values to this array to save changes in the database. This tells me that whatever is in $edit will be saved to the database, however, this is not the case I am seeing.

Is there another step you have to take for your changes to $edit to actually take place? Is Drupal’s documentation incorrect? Is this just some random bug?

EDIT: The array is an array of Entity References, for what it’s worth

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.