Buy Now
Sign in

FAQ search

How can I add a User to a User Group?

Details
Published: Monday, 30 November -0001 00:00
In Joomla! 2.5 there is a new more flexible User Group structure. To make use of this you need to add Users to UserGroups. In ChronoForms you can do this using a Custom Code action with the code in this FAQ.
Here is the simplest form of code needed to assign a User to a User Group. You need to have both the User ID and the Group ID. If you don't' know the Group ID you can look it up in the Site Admin | Users | Groups tab where it is in the right hand column.
<?php
$group_id = 99;
$user_id  = 999;
jimport( 'joomla.user.helper' );
JUserHelper::addUserToGroup($user_id, $group_id);
?>
If this is a newly registered user then this Custom Code action needs to run after the Joomla! Registration action when you can get the new User ID:
<?php
$group_id = 99;
$user_id  = $form->data['_PLUGINS_']['joomla_registration']['id'];
jimport( 'joomla.user.helper' );
JUserHelper::addUserToGroup($user_id, $group_id);
?>
You can, of course, also set the Group ID depending on a form variable. Here's an example where there were regional divisions set up with matching User Groups:
<?php
if ( !isset($form->data['division']) || !$form->data['division'] ) {
  // there is no division selected
  return false;
}
$group_array = array (
'CEN' => '16', //Central
'MDW' => '20', //Mid-West
'MIA' => '13', //Mid-Atlantic
'MIS' => '14', //Mid-South
'NTC' => '18', //North Central
'NTE' => '12', //Northeast
'STE' => '15', //Southeast
'WES' => '17', //Western
);
$group_id = $group_array[$form->data['division']];
$user_id  = $form->data['_PLUGINS_']['joomla_registration']['id'];
jimport( 'joomla.user.helper' );
JUserHelper::addUserToGroup($user_id, $group_id);
?>