background image

Content tagged with: user

Eric's picture

In this tutorial I'll show how you can programmatically and dynamically remove a column from your view. In my example, I chose to hide an email column from unauthenticated users, but you could apply this code to do pretty much anything.

To get things started, I defined a content type of "Profile" to contain some user details (using the Content Profile module) and used the Devel module's generate users and nodes functionality to create some sample data. I then created a view to show the data:

Here is my page view display:

Now you can add the hook_views_pre_build() function in your module. Since the $view object is large, I recommend using krumo() (which comes with the Devel module) to browse through the $view object's properties.

<?php
function MYMODULE_views_pre_build(&$view) {

 
// check for your view name (in my example: people)
 
if ($view->name=='people') {
   
krumo($view);
  }

}
?>

The above code will neatly format the $view object in a hierarchical display. You can click to expand each class property.

As you can see, the $view object has a lot of data in it. At this point, you'll need to get acquainted with the structure of the handler object of the view ($view->display['default']->handler) and determine what to modify. To remove the email column for unauthenticated users, you can add the following code:

<?php
function MYMODULE_views_pre_build(&$view) {

 
// check for your view name (in my example: people)
 
if ($view->name=='people') {
  
   
// check if the user is anon
   
if (in_array('anonymous user',$GLOBALS['user']->roles)) {

     
// remove view hander properties for email column
     
unset(
       
$view->display['default']->handler->options['fields']['mail'],
       
$view->display['default']->handler->options['style_options']['columns']['mail'],
       
$view->display['default']->handler->options['style_options']['info']['mail']
      );

    }

  }

}
?>

When I logout, my view no longer shows the email column:

Eric's picture

In this blog entry I'll show how you can create a Google map showing where your users are located using CCK, Content Profile, Views, GMap, and Location modules. Once you've downloaded and extracted those modules, enable the following modules (and set permissions accordingly):

Content
Location
Location CCK
Content Profile
GMap
GMap Location
Views
Views UI

Next you'll need to configure these new modules. On the GMap settings page (admin/settings/gmap) you'll need to add your API Key and enable the setting to Use AutoZoom. On the Location settings page (admin/settings/location) enable the checkbox to use a Google Map to set latitude and longitude and enable JIT geocoding. On the geocoding settings page (admin/settings/location/geocoding), you'll have to enable Google Maps for the desired countries.

The Content Profile module creates a new content type called "Profile". You'll need to add a new field to this content type for the user's location (admin/content/node-type/profile/fields). Enter a label for the node type (Location), enter a field name (field_location), choose "Location" for the field type, and choose "Location Field" for the widget.

On the next screen edit the Locative information sections (Collection and Display) to your liking, and save the field settings. For my example, I enabled Street location, Additional, City, State, Postal code, Country, and Coordinate Chooser.

Now if you create your profile node (node/add/profile) you can enter your location information and save the new node. If all is working at this point, if you return to the profile node edit screen and scroll down to the location information, you should now see a marker on map for your location and the geocoded information will be shown.

Now you can add a new view (admin/build/views/add) to show the user's profile locations. Enter a name for your view, choose node for the view type, and click the next button. Add a new filter for "Node: Published" is true and "Node: Type" is one of "Profile". Add a new relationship for Content: Location (field_location). Add fields for "Location: Latitude" (using the Location relationship), "Location: Longitude" (using the Location relationship), and any additional fields you'd like to display in the GMap marker (title, parts of the address, etc). For the Style of the view choose "GMap". For the GMap style settings, select "Choose latitude and longitude fields" for the Data Source and ensure the Latitude and Longitude fields as set.

Lastly, I added a page view so I could see the results in action..

ps> special thanks to everyone at CommonPlaces for their great technical discussions about these modules!

Eric's picture

Here's a quick code snippet I use to programmatically create new users:

<?php
$newUser
= array(
 
'name' => 'username',
 
'pass' => 'password', // note: do not md5 the password
 
'mail' => 'email address',
 
'status' => 1,
 
'init' => 'email address'
);           
user_save(null, $newUser);
?>

And, here's how you can update an existing user:

<?php
// load user object
$existingUser = user_load('USERID');

// update some user property
$existingUser->some_property = 'blah';

// save existing user
user_save((object) array('uid' => $existingUser->uid), (array) $existingUser);
?>

If you wanted to update an existing user's profile data:

<?php
// load user object
$existingUser = user_load('USERID');

// create an array of properties to update
$edit = array(
 
'profile_first_name' => 'Eric'
);

// save existing user
user_save(
  (object) array(
'uid' => $existingUser->uid),
 
$edit,
 
'Personal Information' // category
);
?>

Eric's picture

In this blog entry, I'll show you how you can add some module code to allow users to select different themes for their profile page. I decided to use the standard user-profile.tpl.php as the base template. I copied this file into my theme folder and replicated it a few times. I named the files:

user-profile-version-1.tpl.php
user-profile-version-2.tpl.php

For my example, I simply added the text "Version 1" and "Version 2" to the top of these files to show it's working, but you could revise the layout, add CSS, etc.

Next, I created a module to contain all the following code. I defined a hook_perm() and hook_menu() function to add a menu local task (tab) to the user page.

<?php
function MYMODULE_perm() {
  return array(
   
'choose profile theme'
 
);
}

function
MYMODULE_menu() {
 
 
$items = array();
 
 
$items['user/%user/choose-profile-them'] = array(
   
'title' => 'Choose Profile Theme',
   
'page callback' => '_MYMODULE_callback_choose_profile_theme',
   
'page arguments' => array(1),
   
'access callback' => 'user_access',
   
'access arguments' => array('choose profile theme'),
   
'type' => MENU_LOCAL_TASK,
  );
 
  return
$items;
 
}
?>

user profile tab

Next, I defined the page callback to create a list of available templates for the user to choose from.

<?php
function _MYMODULE_callback_choose_profile_theme($user) {

 
// create an empty strong variable for page html
 
$html = "";

 
// define a list of available profile templates
 
$profileTemplates = array(
   
'user-profile-version-1' => 'Version 1',
   
'user-profile-version-2' => 'Version 2'
 
);
 
 
// loop through templates and ensure they exist
 
foreach ($profileTemplates as $template => $name) {
    if (!
file_exists(path_to_theme() . '/' . $template . '.tpl.php')) {
      unset(
$profileTemplates[$name]); 
    }
  }
 
  if (
count($profileTemplates)) {
   
$html .= drupal_get_form('_MYMODULE_callback_choose_profile_theme_form', $user, $profileTemplates);
  } else {
   
$html .= "No profile themes currently exist.";
  }
 
  return
$html;
 
}
?>

The following functions define the form array, and validation and submit handlers. When the form is submitted, the template option is saved to the user account variables using the user_save() function.

<?php
function _MYMODULE_callback_choose_profile_theme_form($form_state, $user, $profileTemplates) {

 
$form = array();
 
 
// add a select input element
 
$form['profileTemplate'] = array(
   
'#type' => 'select',
   
'#title' => t('Profile Template'),
   
'#options' => $profileTemplates,
   
'#default_value' => $GLOBALS['user']->profileTemplate
 
);
 
 
// add a submit button
 
$form['submit'] = array(
   
'#type' => 'submit',
   
'#value' => t('Submit')
  );
 
 
// add hidden element for userID
 
$form['userID'] = array(
   
'#type' => 'hidden',
   
'#value' => $user->uid
 
);
 
  return
$form;
}

function
_MYMODULE_callback_choose_profile_theme_form_validate($form, &$form_state) {
 
// TODO: add your additional form validation here
 
  // ensure userID submitted matches current user
 
if ($form_state['values']['userID']!=$GLOBALS['user']->uid) {
   
form_set_error('', t('Error processing form.')); 
  }
 
}

function
_MYMODULE_callback_choose_profile_theme_form_submit($form, &$form_state) {

 
// load user object
 
$user = user_load($form_state['values']['userID']);
 
 
// save profile template to user variables
 
user_save($user, array('profileTemplate' => $form_state['values']['profileTemplate']));
 
 
// set a message
 
drupal_set_message('Your profile template has been set.');
 
}
?>

user profile form

Last, I defined the preprocess function to see if a template has been set in the user variables, and add the templates suggestion to change the user profile template.

<?php
function MYMODULE_preprocess_user_profile(&$variables) {

 
// ensure the template file exists, and is set in the user object
 
if (file_exists(path_to_theme() . '/' . $variables['user']->profileTemplate . '.tpl.php') && $variables['user']->profileTemplate) {

   
// set a templates suggestion
   
$variables['template_files'][] = $variables['user']->profileTemplate;
  }
 
}
?>

As you can see below, when I choose the "Version 2" template option, the file "user-profile-version-2.tpl.php" is being loaded, and the text "Version 2" is displayed at the top of the page.

user profile selected

Eric's picture

At some point, you might want to restrict sections of a form to certain users and roles. That can be accomplished relatively easy by creating a module that implements 2 Drupal hooks: hook_form_alter and hook_perm.

First, I start by adding the hook_perm():

<?php
function MYMODULE_perm() {
 
// return an array of permissions,
  // they can be named whatever you'd like.
  // NOTE: avoid redeclaring permissions that are already set
 
return array('access secret section of my form');
}
?>

Next, add a form_alter hook:

<?php
function MYMODULE_form_alter(&$form, $form_state, $form_id) {

 
// test for the form id you'd like to alter.
  // if you are unsure of the it's exact name,
  // you could add this: echo $form_id . "<BR>";
 
if ($form_id =='SOME_FORM_ID') {
   
// check if the user has access to the permission you defined
   
if (!user_access('access secret section of my form')) {
     
// deny access to the form element
      // if you don't what what it's called,
      // output the $form object:
      // echo "<pre>" . print_r($form, true) . "</pre>";
     
$form['SOME_FORM_ELEMENT']['#access'] = false;
    }
  }
}
?>

Now, if you enable you module you can restrict permissions by going here: /admin/user/permissions