I need to migrate users from an other app into TYPO3 and are not able to set the user group of new users. Updating existing users and adding the group works.
Here is my code.
/**
* @var \TYPO3\CMS\Extbase\Domain\Repository\FrontendUserRepository
*/
protected $userRepository;
/**
* @var \TYPO3\CMS\Extbase\Domain\Repository\FrontendUserGroupRepository
*/
protected $userGroupRepository;
/**
* @var \TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager
*/
protected $persistenceManager;
...
$this->userGroup = $this->userGroupRepository->findOneByTitle('My desired group');
$this->userGroupStorage = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
$this->userGroupStorage->attach($this->userGroup);
$user = $this->userRepository->findOneByForeignId($id);
if ($user) {
$this->updateUserData($user);
$this->userRepository->update($user);
} else {
$user = new \TYPO3\CMS\Extbase\Domain\Model\FrontendUser();
$this->updateUserData($user);
$this->userRepository->add($user);
}
$this->persistenceManager->persistAll();
...
private function updateUserData($user)
{
$user->setPid($this->pid);
$user->setFirstName($this->firstName);
...
// I use either this or the other line, not both at the same time!
// works on new and existing users but never gets persisted
$user->setUsergroup($this->userGroupStorage);
// throws error on new user but gets persisted on existing users
$user->addUsergroup($this->userGroup);
}
Why is the UserGroupStorage not sored in the database? My workaround would be creating the user persist it, reload it from the database and add the user group. But that's no good practice.
Finally I found a solution (or workaround).
This way I don't get an error message for new users and the changes are always stored in the database.