The Profile2 module for Drupal 7 enables the creation of multiple profile types, which can then be assigned to roles via permissions. Profile2 includes a "Profile pages" feature, allowing each profile to have a unique page with its own URL and menu link (e.g., "My Profile"). However, these URLs may not always be user-friendly.
To improve the user experience, we can use the Pathauto module to create custom aliases for Profile2 profiles, especially when users register or update their profiles. This guide explains how to set up aliases so that every user in the application has a Profile2 called "company" and can be accessed more easily by their company name.
Steps to Create a Custom Alias with Profile2
- Define the Alias Format: Decide on a URL format for the alias. We’ll use
/company/{company_name}
, making it easy to remember and access. - Detect Profile Creation or Update: Identify when a Profile2 profile is created or edited by using the
hook_profile2_presave
hook provided by the Profile2 API. This hook triggers when a Profile2 entry is inserted or updated in the database. - Sanitize the Company Name: Use Pathauto’s
pathauto_cleanstring
function and a customtoAscii
function to ensure the company name is suitable for URL usage. - Check for Existing Aliases: Ensure each company name is unique by checking if an alias already exists. If an alias already exists, it indicates that the company profile is being edited, so we delete the old alias and create a new one.
- Save the Alias: Once sanitized and confirmed unique, save the alias, allowing users to access their profile with a more user-friendly URL.
Implementing the Alias Functionality
The hook_profile2_presave
function executes when a Profile2 is saved. Here’s a brief look at the implementation:
This code first retrieves the current company name, converts it to ASCII, and sanitizes it. If an existing alias is detected, the old alias is deleted. The new sanitized alias is then saved, ensuring users can access profiles via /company/{company_name}
.
Conclusion
This custom module provides a streamlined way to access Profile2 profiles in Drupal 7 with user-friendly URLs, enhancing the application’s usability. By leveraging Profile2 and Pathauto, we’ve created a solution that maintains unique, accessible URLs for each company profile.