error assign an account to a security group

Hello, everyone,
I’m trying to assign an Account to a Security Group whose id I know. I have followed the documentation and some advice on various posts but when I launch the code I always get an error.
I report the portion of the code:

// the Account Bean
$aziendaBean=BeanFactory::getBean('Accounts','542c9fa2-185f-7b8a-71ae-5d2f9aec3557');

// The Security Group Bean
$securityBean=BeanFactory::getBean('SecurityGroups');
$securityBean->retrieve_by_string_fields(array('name'=>'GDS aziende Elinet','deleted'=>0));
$securityBean->load_relationship('accounts');
$securityBean->accounts->add('542c9fa2-185f-7b8a-71ae-5d2f9aec3557');

This is the generated php error:

Notice: Undefined property: SecurityGroup::$accounts in /var/www/sites/x-crm-dev/custom/TheImportEntryPoint.php on line 47

Fatal error: Uncaught Error: Call to a member function add() on null in /var/www/sites/x-crm-dev/custom/TheImportEntryPoint.php:47 Stack trace: #0 /var/www/sites/x-crm-dev/include/MVC/Controller/SugarController.php(1020): require_once() #1 /var/www/sites/x-crm-dev/include/MVC/Controller/SugarController.php(468): SugarController->handleEntryPoint() #2 /var/www/sites/x-crm-dev/include/MVC/Controller/SugarController.php(373): SugarController->process() #3 /var/www/sites/x-crm-dev/include/MVC/SugarApplication.php(113): SugarController->execute() #4 /var/www/sites/x-crm-dev/index.php(52): SugarApplication->execute() #5 {main} thrown in /var/www/sites/x-crm-dev/custom/TheImportEntryPoint.php on line 47

The call to the add() method seems to fail…

I don’t think you can call that relationship Accounts. You can call SecurityGroups instead

Because you know the the account, you can use:

$rel_name = 'SecurityGroups';
$aziendaBean->load_relationship($rel_name); // We load the relationship
	// Please note that by default all assigned security groups to user
	// will be related to this new account. To solve that we remove all related security groups first
//$aziendaBean->$rel_name->delete($$aziendaBean->id);// use this line if you want to delete all relationships
$aziendaBean->$rel_name->add('Your Security Group ID');
1 Like

Hello AlxGr,
it works, I was wrong about the call to the relationship.
Thank you