How can a plugin add a user profile field?

How can a plugin add a user profile field?

by Juris Evertovskis -
Number of replies: 2

We need a couple of profile fields added when installing a plugin. Is there any API for that? Or is manual insertion into `mdl_user_info_field` the only way to accomplish that?

I found an old issue on the tracker, but that seems to have been dropped at the time: https://tracker.moodle.org/browse/MDL-26347  Has something changed over the last decade? smile

Average of ratings: Useful (1)
In reply to Juris Evertovskis

Re: How can a plugin add a user profile field?

by Tim Hunt -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

You can put code like this in the upgrade.php / install.php for your plugin:

if (!$DB->record_exists('user_info_field',
['shortname' => self::USER_FIELD_USERTYPE, 'categoryid' => $category->id])) {
$field = (object)[
'shortname' => self::USER_FIELD_USERTYPE,
'name' => 'User type',
'datatype' => 'text',
'description' => '',
'categoryid' => $category->id,
'sortorder' => 4,
'locked' => 1,
'defaultdata' => '',
'param1' => 16, // Display size.
'param2' => 128 // Max length.
];
$errors = $define->define_validate($field, []);
if (empty($errors)) {
$define->define_save($field);
} else {
throw new \coding_exception('Invalid user info field', $errors);
}
}

Average of ratings: Useful (2)