This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

billyZduke
billyZduke

I don't see a definitive answer for this in my searching, but several times already I've come up against this issue. There are plenty of methods available to extend the properties of a model in the plugin.php file,, but is it possible to add new methods via Model::extend(), without having to create a new extended class definition file?

In my case, I'm extending RainLab.User (a common need among October developers, if one judges by the number of forum topics already posted relating to this). I can addFillable(), addDateAttribute(), augment the model's validation $rules, $jsonable, and relation values, but I can't seem to get the following to produce the desired result:

In plugin.php:

    public function boot()
    {
        UserModel::extend(function($model)
        {
            $model->newMethod = function() {
                return 'anything';
            };
        }
    }

In twig template:

    {{ dump(user.newMethod()) }}
Surahman
Surahman

Hi Billy, You can add new method by using this example code,

public function boot() 
{
    UserModel::extend(function($model) {
        $model->addDynamicMethod('yourNewMethod', function($value) use ($model) {
            $this->name = $value;
        });
    });
}

1-2 of 2

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.