Skip to main content Skip to page footer

Cloning of database entries in Extbase extensions

Often a function is needed to duplicate entries in Extbase extensions. Here is one method on how to do it.

In this blog post I will show how to copy database entries in Extbase extensions in a frontend controller in an Extbase extensions.

Implementation in extension Controller

I could find a helpful function on Stackoverflow while I was upgrading an Extbase extension from TYPO3 9 to TYPO3 10.

Before the extension used a backend user session to use the BackendUtility to copy database entries.

The following function from Stackoverflow I used to copy domain models:

/**
 * @param object $object
 * @return object
 * @throws Exception
 */
protected function deepcopy($object)
{
	$clone = $this->objectManager->get(get_class($object));
	$properties = ObjectAccess::getGettableProperties($object);
	foreach ($properties as $propertyName => $propertyValue) {
		if ($propertyValue instanceof ObjectStorage) {
			$v = $this->objectManager->get(ObjectStorage::class);
			foreach ($propertyValue as $subObject) {
				$subClone = $this->deepcopy($subObject);
				$v->attach($subClone);
			}
		} else {
			$v = $propertyValue;
		}
		if ($v !== null) {
			ObjectAccess::setProperty($clone, $propertyName, $v);
		}
	}
	return $clone;
}

 

In your own Controller you could use this function in your own copy function like this:

/**
 * @param MyModel $myModel
 * @return MyModel|null
 * @throws Exception
 */
protected function copyModel($myModel)
{
	/** @var $myModel MyModel */
	$newModel = $this->deepcopy($myModel);
	if ($newModel) {
		$newModel->setProperty('value');
		$this->myModelRepository->add($newModel);
		$this->persistenceManager->persistAll();
	}
	return $newModel;
}