OctoberCMS How to Override Users Plugin onRegister() Function?

- 1 answer

Ad

I'm using OctoberCMS based on Laravel.

I'm trying to override the Users PluginonRegister() function.

A previous answer helped me extend the plugin.

I want to restrict Usernames to alphanumeric only with alpha_dash and limit to 50 characters.

The original function in Account.php

public function onRegister()
{
...
    if ($this->loginAttribute() == UserSettings::LOGIN_USERNAME) {
        $rules['username'] = 'required|between:2,255';
    }

My Override

Users Events docs https://github.com/rainlab/user-plugin#events

public function boot() {

    \RainLab\User\Models\User::extend(function($model) {

        $model->bindEvent('model.beforeUpdate', function() use ($model) {

            # User Register
            \Event::listen('rainlab.user.register', function($user, $data) {

                if ($this->loginAttribute() == UserSettings::LOGIN_USERNAME) {
                    $rules['username'] = 'required|alpha_dash|between:2,50';
                }

            });
        }); 
    }); 
}

Error

"Call to undefined method [loginAttribute]"

If I remove the if statement and loginAttribute and use only $rules['username'], I am still able to register names with non-alphanumeric characters.

I have been able to extend new code using this, but not override existing code.

Ad

Answer

Ad

I don't think you understand the page cycle here.

rainlab.user.register is called after the user has already been registered. I.e. they have already passed validation and already exist with the invalid username.

What you can do instead is bind to the User model's model.beforeSave event and do your own validation of the username:

public function boot() {

    \RainLab\User\Models\User::extend(function($model) {

        $model->bindEvent('model.beforeSave', function() use ($model) {
            $validator = \Validator::make($model->attributes, [
                'username' => 'required|alpha_dash|between:2,50',
            ]);

            if ($validator->fails()) {
                throw new \ValidationException([
                    'username' => 'Username must contain alphanumeric values only, and be between 2 and 50 characters in length',
                ]);
            }
        });

    });

}
Ad
source: stackoverflow.com
Ad