简体   繁体   中英

OctoberCMS How to Override Users Plugin onRegister() Function?

I'm using OctoberCMS based on Laravel.

I'm trying to override the Users Plugin onRegister() 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.

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

rainlab.user.register is called after the user has already been registered. Ie 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',
                ]);
            }
        });

    });

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM