Add extra fields to User model or other model

Sometime you need to add extra fields to a model. You will find the official documentation here : https://octobercms.com/docs/plugin/extending#extending-user-mode

I prefer using an external YAML file to configre my extra fields and keep Plugin.php small.

public function boot()
{
    $this->registerUserExtraFields();
}

private function registerUserExtraFields()
{
    $userFields = Yaml::parseFile(__DIR__ . '/models/users/custom_fields.yaml');

    UserModel::extend(function (UserModel $model) use ($userFields) {
        $model->addFillable(array_keys($userFields));
    });

    UsersController::extendFormFields(function (Form $widget) use ($userFields) {
        // Prevent extending of related form instead of the intended User form
        if (!$widget->model instanceof UserModel) {
            return;
        }
        $widget->addTabFields($userFields);
    });
}

Create a YAML file in myplugin/models/users/custom_fields.yaml with your fields

fielda:
    label: Field A
    type: text
    span: auto
    tab: MyTab
fieldb:
    label: Discount B
    type: text
    span: auto
    tab: MyTab

Posted in OctoberCMS on Jan 29, 2019