Altering Profile Field (profile.module) View Functionality

Posted on: 2008-12-11 11:33:02

Someone here at DIWD had a question on how to modify a view (in Views 1.6) that uses profile fields (defined with profile.module). The specific idea was taking a "name" field and making it link to the user profile. This can be done with two functions defined in a module.

For this particular scenario, we created a module specifically for this called obs.module (named for Austin Smith's obs module during his "NYO Site Dissection @ DIWD":http://www.doitwithdrupal.com/sessions/site-dissection-new-york-observer ). In it, we define two functions:

This first function implements view's views_tables_alter hook. This allows us to alter the huge "tables array generated by hook_views_tables":http://drupal.org/handbook/modules/views/api. The stuff we want to change is auto-generated by the default installation of views (which comes with profiles support). You'll have to put the name of your field in here (you can find it while editing your profile).

<code lang="php">function obs_views_tables_alter(&$table) { $table['profile_display_name']['fields']['value']['handler'] = 'obs_profile_name_handler'; $table['profile_display_name']['fields']['value']['uid'] = 'uid'; $table['profile_display_name']['fields']['value']['addlfields'] = array('uid'); }

The first line of the function sets up our output handler. The second maps the uid value to the uid field and the third pulls the uid field out of the profile_values table so that we can access it. We'll need it to generate the link to the user's profile.

The next function we add is the handler for the field, which just renders the field. Pretty simple here:

<code lang="php">function obs_profile_name_handler($fieldinfo, $fielddata, $value, $data) { $value = (unserialize($value) === false) ? $value : unserialize($value); return l($value,'user/'.$data->profile_display_name_uid); }

Pretty much it's copied verbatim as the default handler for profile fields in the views module but adds the link and returns that instead of the value.

Not that for your field, you'll have to replace any instance of profile_display_name with the name of your profile field.

Hope that helps!