Page 1 of 1
How to create User Group Progamatically
Posted: Sun Mar 24, 2024 1:43 pm
by cscotthosting
Hello,
I have seen a bunch of examples in google searches and here on how to add a user to Joomla 5.
However, I am in need of adding the creation of a User Group when a user is created, progamatically.
Can someone assist with the code to create a User Group.
Thanks
Re: How to create User Group Progamatically
Posted: Sun Mar 24, 2024 4:27 pm
by pe7er
Welcome to Joomla forum!
In Joomla 5 you can probably create a new User Group with something like the code below:
Code: Select all
use Joomla\CMS\Factory;
use Joomla\Component\Users\Administrator\Model\GroupModel;
$group = [
'id' => 0,
'title' => 'Your new User Group Name',
'parent_id' => 1
];
Factory::getApplication()->bootComponent('com_users');
$model = new GroupModel;
if (!$model->save($group)) {
Factory::getApplication()->enqueueMessage($model->getError(), 'error');
return false;
}
Re: How to create User Group Progamatically
Posted: Mon Mar 25, 2024 10:50 am
by cscotthosting
Worked like a charm, Thank You. Lastly, how do I get the id of the newly created group?
I tried {var:php9.id}, outside the php block, but that did not work. I have a Joomla Message that displays the new id for the user and the group...
The User {data:username} userid= {var:joomla_user7.id} and groupid = {var:php9.id} has been added.
Re: How to create User Group Progamatically
Posted: Wed Mar 27, 2024 9:16 am
by cscotthosting
Anyone?
Lastly, how do I get the id of the newly created group?
I tried {var:php9.id}, outside the php block, but that did not work. I have a Joomla Message that displays the new id for the user and the group...
The User {data:username} userid= {var:joomla_user7.id} and groupid = {var:php9.id} has been added.
Re: How to create User Group Progamatically
Posted: Wed Mar 27, 2024 11:21 am
by MarkRS
cscotthosting wrote: ↑Wed Mar 27, 2024 9:16 am
Anyone?
Lastly, how do I get the id of the newly created group?
I've not done this, but my guess would be
Code: Select all
$yourNewGroup->getTable()->getId();
Re: How to create User Group Progamatically
Posted: Wed Mar 27, 2024 12:44 pm
by cscotthosting
Thanks MarkRS
What is $yourNewGroup. Is that the new group name that was created or literally the text I use in my code?
Re: How to create User Group Progamatically
Posted: Wed Mar 27, 2024 3:52 pm
by MarkRS
Yes, poor reply of mine, sorry.
I mean the groupModel object.