7

I recently developed a module where I used the function hook_form_user_profile_form_alter(&$form, &$form_state) to capture user preferences and saved them using function hook_user_presave(&$edit, $account, $category) . Then I accessed the data using $user->data['field'] in a module . That worked fine .

But now I want to store the same preferences using another form (not the user profile form). So is there any other hook to store them ?

I want to give a link to each user to the page(form other than the user profile ) where he can store his preferences .

Thanks in advance.

2 Answers 2

8

You don't need to use a hook you need to use the API function user_save(). Which is a very weird function because unlike all other save functions, it has a separate argument for the things that you want to change.

Something like this should work, in your submit callback:

<?php
// Make sure you are working with the fully loaded user object.
$account = user_load($GLOBALS['user']->uid);
$edit['data']['your_stuff'] = $whatever;
user_save($account, $edit);
?>

FYI: user_save() is no more in Drupal 8 and instead behaves like all other entity save functions/methods in 8.x, by calling $account->save() after changing $account. See the following change record for details: http://drupal.org/node/1554986

3
  • 1
    Also, you might want to consider saving your information in a separate table that references the uid. Downside is that the information isn't loaded by default but the plus side is that it doesn't have to be loaded all the time and you can query it directly (e.g. check the setting of a user based on the uid without having to load the whole object).
    – Berdir
    Jun 16, 2012 at 22:36
  • Thanks a lot . your code worked. I will use a separate table if the no of preferences of user are more :) Jun 18, 2012 at 12:51
  • 1
    sure I will . But I have only 8 reputation for now and 15 is required for upvote . I will upvote after I achive 15 :) Jun 19, 2012 at 3:12
0

Well you can always create your own form using the Form API with a validate and submit function and save the data where ever you want. That could be in the user data array as well, as it looks to be the perfect place for user related data. You could also create your own table with the Schema API. I think the "submit" function for the form is the "hook" you are looking for.

Form API: http://api.drupal.org/api/drupal/includes%21form.inc/group/form_api/7

Schema API: http://api.drupal.org/api/drupal/includes%21database%21schema.inc/group/schemaapi/7

1
  • I am comfortable creating form. But I am not able to save it in user data. In form submit what should I do to achieve this? I believe its something with user_presave but I don't know how to use it in this context. Jun 16, 2012 at 13:02

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.