OctoberCMS如何覆盖用户插件的onRegister()函数? [英] OctoberCMS How to Override Users Plugin onRegister() Function?

查看:77
本文介绍了OctoberCMS如何覆盖用户插件的onRegister()函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用基于Laravel的 OctoberCMS .

I'm using OctoberCMS based on Laravel.

我正在尝试覆盖用户插件 onRegister()函数.

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

先前的答案帮助我扩展了插件.

我想只用alpha_dash将用户名限制为字母数字,并且限制为50个字符.

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

Account.php

The original function in Account.php

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

我的替代

用户事件文档 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';
                }

            });
        }); 
    }); 
}

错误

"Call to undefined method [loginAttribute]"

如果删除if语句和loginAttribute并仅使用$ rules ['username'],我仍然可以使用非字母数字字符注册名称.

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在用户已经注册之后被称为. IE.他们已经通过验证,并且已经以无效的用户名存在.

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.

相反,您可以做的是绑定到User模型的model.beforeSave事件,并对用户名进行自己的验证:

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',
                ]);
            }
        });

    });

}

这篇关于OctoberCMS如何覆盖用户插件的onRegister()函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆