Updating User Settings

To change user settings, you’ll need to first load or create the modUserSetting object:

$setting = $modx->getObject('modUserSetting', [
    'key' => 'active_survey_id',
    'user' => $modx->user->get('id')
]);
if (!$setting) {
    $setting = $modx->newObject('modUserSetting');
    $setting->set('key', 'active_survey_id');
    $setting->set('user', $modx->user->get('id');
}

Then set the value and save the modUserSetting object:

$survey = $_POST['idProject'];
// @todo add validation for this value: allowed project? right format/value type? 
$setting->set('value', $survey);

// Save it to the database
$setting->save();

// add it to the UserSettings on the user in memory
$modx->user->addMany($setting, 'UserSettings');

Finally if I recall correctly user settings take an extra step for them to apply in a current session, depending on how you’re using them, because there’s some caching going on in the session itself. I’ve not tested this, but think this should do the trick:

$modx->getUser('', true);

(That relies on having added the setting to the UserSettings in-memory representation as that wont look it up from the database if it has already been loaded before.)

Depending on how you use the setting in your site, redirecting the user (in other words, starting a new request) may be necessary to have that apply.

All in all, I agree with Bruno’s suggestion to use the extended profile field as that’s simpler and has less “gotchas”.

1 Like