Register: Use Email as Username

An easy way to make the user's email address serve as their MODX username


There are some sites where you want the user's username to be their email address. The Register snippet uses the 'email' input field from its form for the email, but it uses the 'username' input field for the username. In this article we'll see an easy way to change that.


MODX logo

Options

When a MODX Forum user asked about this, my first thought was to just call the field 'username' but make the caption as 'Email'. As a long-time programmer, though, this solution seemed to be asking for trouble down the road. Mis-naming form fields is almost never a good way to solve a problem and it can lead to some really frustrating situations when you hit a snag later on and have to come back to maintain the code. Worse, there's the problem of how to get the email into the 'email' field of the User Profile. There's also a chance that it would confuse sight-impaired visitors using screen readers, and cause trouble for people who use any kind of auto-fill option for forms — not to mention the issues with validation and getting validation error message to show up in the right place.

Since I didn't like the first idea, I assumed that the solution would require a custom postHook snippet specified in the Register snippet tag. The snippet would get the value of the 'email' input field from the $_POST array, set it as the value of the 'username' field of the modUser object, and save the user.

As I was looking through the labyrinthine code of the Login package (which Register is a part of), however, I stumbled onto an undocumented property that makes both of the solutions above unnecessary.


The Solution

This couldn't be much easier. The &usernameField property of the Register snippet tells Register which field to use. To use the email field for the username, you need only add this property to the Register Snippet tag:

    &usernameField=`email`

With this property, the value of the 'email' input field can be validated as an email, but will be automatically written to the 'username' field of the modUser object. Better yet, the value will also be written to the 'email' field of the modUserProfile object. If it's not a valid email, the error message will show up where it should. It's a great solution, and really simple to implement.


Coming Up

In the next article, we'll look at some ways to hide things in the MODX Manager using CSS.


For more information on how to use MODX to create a web site, see my web site Bob's Guides, or better yet, buy my book: MODX: The Official Guide.

Looking for high-quality, MODX-friendly hosting? As of May 2016, Bob's Guides is hosted at Hosting.com (formerly A2 Hosting). (More information in the box below.)



Comments (0)


Please login to comment.

  (Login)