Login

My Profile - Persisting User Profile Data

In part 1 of this series we showed you how to custom the Drupal account registration form. We now need to make sure that the new data is stored in the database (after a user completes the user registration form).

We implement hook_user()

function my_profile_user($op, &$edit, &$account, $category = NULL) {
   switch($op) {
        case 'insert' :
            addAlias($edit['alias'],$edit['uid']);
        break;
 
        case 'delete' :
           deleteAlias($edit['_account']->uid);
        break;
   }
}

We also added some simple custom functions: addAlias() and deleteAlias(). Detailed below:

function addAlias($alias, $uid) {
    $mp = new my_profile();
    $mp->setAlias($alias);
    $mp->setUid($uid);
 
    $dbMp = new dbMy_profile();
    $mp = $dbMp->insert($mp);
    return $mp;
}
 
function deleteAlias($uid) {
    $dbMp = new dbMy_profile();
    $op_result = $dbMp->delete($uid);
    return $op_result;
}

Explanation:

First we decided to keep our hook_user implementation as sparse as possible. Therefore, we created the two utility methods add and delete alias.

In part 2, we detailed our 2 classes. AddAlias creates a new instance of the my_profile class and then passes to the database access object dbMy_profile().

The idea is to keep things simple and only detail the requirement at hand. Thus. we don't detail all of the database connection and insert statements in the AddAlias method. Those details are delegated to the class objects.

We started this post by stating we needed to guarantee our custom data was saved. Well we also need to make sure that data can be removed. Since, we've added our data logically to a "user account", it makes sense that our data is removed when the account is deleted. That's why we capture the delete operation (in hook_user) and call our deleteAlias() method.

In the next post will show you how to create a maintenance table. That will allow an administrator to Add, Modify or Delete an instance of our custom data (My Profile-Alias).