0

I build my extbased TYPO3 extension in TYPO3 8.7 . It is a Backend-Module. In the controller, i write my own action to clone the object. In this example, i want to clone/duplicate the object 'Campaign' and safe it with a modified title, like add the 'copy' text to the title. But the new object should have also its own new child elements that must be exact copies. When the action is called, i get only a copy of the Object, but no childs. Is there an example or best case how to handle this task? I did not find, even i found some questions and answers that are on the same topic, but older version. i hope that upd to date, there is a more straight forward solution. Thank you for every hint that points me to the right ideas and maybe an up to date and version example. Here is what i have i my controller. How do i implement recursiv copying of all child elements (and some childs have childs, too)?

    /**
     * action clone
     * @param \ABC\Copytest\Domain\Model\Campaign $campaign
     * @return void
     * @var \ABC\Copytest\Domain\Model\Campaign $newCampaign
     */

    public function cloneAction(\ABC\Copytest\Domain\Model\Campaign $campaign) {
        $newCampaign = $this->objectManager->get("ABC\Copytest\Domain\Model\Campaign");
        $properties = $campaign->_getProperties();
        unset($properties['uid']);
        foreach ($properties as $key => $value) {
            $newCampaign->_setProperty($key, $value);
        }
        $newCampaign->_setProperty('title', $properties['title']. ' COPY');
        $this->campaignRepository->add($newCampaign);
        $this->addFlashMessage('Clone was created', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
        $this->redirect('list');
    }

4 Answers 4

4

I am aware that this question has been answered a long time ago. But I want to provide my solution to create a deep copy for further reference. Tested on TYPO3 9.5.8.

private function deepcopy($object)
{
    $clone = $this->objectManager->get(get_class($object));
    $properties = \TYPO3\CMS\Extbase\Reflection\ObjectAccess::getGettableProperties($object);
    foreach ($properties as $propertyName => $propertyValue) {
        if ($propertyValue instanceof \TYPO3\CMS\Extbase\Persistence\ObjectStorage) {
            $v = $this->objectManager->get(\TYPO3\CMS\Extbase\Persistence\ObjectStorage::class);
            foreach($propertyValue as $subObject) {
                $subClone = $this->deepcopy($subObject);
                $v->attach($subClone);
            }
        } else { 
            $v = $propertyValue;
        }
        if ($v !== null) {
            \TYPO3\CMS\Extbase\Reflection\ObjectAccess::setProperty($clone, $propertyName, $v);
        }
    }
    return $clone;
}
3
  • Thanks! One small thing to add if f.e. image is empty:if(null !== $v) { \TYPO3\CMS\Extbase\Reflection\ObjectAccess::setProperty($clone, $propertyName, $v); }
    – matin
    Dec 30, 2019 at 13:13
  • Thanks martin, I added that part.
    – Markus
    Jan 15, 2020 at 14:18
  • I finally came back to the project and could now implement this solution. Thank you Markus.
    – DeppDeeh
    Jul 17, 2020 at 10:04
0

There is one approach which tackles this usecase from a different POV, namely that request argument values without an identity are automatically put into fresh objects which can then be persisted. This basically clones the original objects. This is what you need to do:

  1. Add a view which has fields for all properties of your object, hidden fields are fine too. This can for example be an edit view with a separate submit button to call your clone action.
  2. Add a initializeCloneAction() and get the raw request arguments via $this->request->getArguments().
  3. Now do unset($arguments[<argumentName>]['__identity']);, do the same for every relation your object has if you want copies instead of shared references.
  4. Store the raw request arguments again via $this->request->setArguments($arguments).
  5. Finally allow the creation of new objects in the property mapping configuration of your argument and possibly all relation properties.

This is how a full initializeCloneAction() could look like:

public function initializeCloneAction()
{
    $arguments = $this->request->getArguments();

    unset(
        $arguments['campaign']['__identity'],
        $arguments['campaign']['singleRelation']['__identity'],
    );

    foreach (array_keys($arguments['campaign']['multiRelation']) as $i) {
        unset($arguments['campaign']['multiRelation'][$i]['__identity']);
    }

    $this->request->setArguments($arguments);

    // Allow object creation now that we have new objects
    $this->arguments->getArgument('campaign')->getPropertyMappingConfiguration()
        ->setTypeConverterOption(PersistentObjectConverter::class, PersistentObjectConverter::CONFIGURATION_CREATION_ALLOWED, true)
        ->allowCreationForSubProperty('singleRelation')
        ->getConfigurationFor('multiRelation')
            ->allowCreationForSubProperty('*');
}

Now if you submit your form using the clone action, your clone action will get a fully populated but new object which you can store in your repository as usual. Your cloneAction() will then be very simple:

public function cloneAction(Campaign $campaign)
{
    $this->campaignRepository->add($campaign);

    $this->addFlashMessage('Campaign was copied successfully!');
    $this->redirect('list');
}
17
  • Thank you for this whole example and idea. I am still trying to get it working. I built a simple extension with on model that has only one 1:n relation to have an easy test szenarion. I struggle with this part in the initializeCloneAction right now: foreach (array_keys($arguments['campaign']['multiRelation']) as $i) { unset($arguments['campaign']['multiRelation'][$i]['__identity']); } I get the Error: PHP Warning: array_keys() expects parameter 1 to be array, null given
    – DeppDeeh
    Sep 4, 2018 at 8:20
  • I changed the code to fit to my model like this: foreach (array_keys($arguments['campaign']['phase']) as $i) { unset($arguments['campaign']['phase'][$i]['__identity']); } But it dont work yet. What am I doing wrong?
    – DeppDeeh
    Sep 4, 2018 at 8:29
  • What exactly doesn't work? Did you make sure to have a field for every object, you need all properties of all related objects too, at least as hidden fields. Sep 4, 2018 at 8:47
  • I get the Error: PHP Warning: array_keys() expects parameter 1 to be array, null given. This is when I call the cloneAction. All the models (Campaign-Model with two 1:n Childs called Phase) have only one property 'title' right now, to keep testing simple. These titles are correctly shown in the form-fields of the page where i then call the cloneAction. Is there any extension in the TER you know about, that uses kind of cloneAction, so I could have a look at the whole code. I didnt find one yet.
    – DeppDeeh
    Sep 4, 2018 at 9:16
  • No, there is no public extension AFAIK. Notice that you should leave off the relation parts if you don't have any relations ATM. Otherwise you need to ensure you have fields for these as mentioned. Sep 5, 2018 at 10:13
0

If you have "LazyLoadingProxy" instance in your object you need add one more conditions.

if ($propertyValue instanceof \TYPO3\CMS\Extbase\Persistence\Generic\LazyLoadingProxy) {
   $objectStorage = $propertyValue->_loadRealInstance();
}

This is my solution for "deepcopy" function:

    private function deepcopy($object)
    {
        $clone = $this->objectManager->get(get_class($object));
        $properties = \TYPO3\CMS\Extbase\Reflection\ObjectAccess::getGettableProperties($object);
        foreach ($properties as $propertyName => $propertyValue) {
            if ($propertyValue instanceof \TYPO3\CMS\Extbase\Persistence\ObjectStorage) {
                $objectStorage = $this->objectManager->get(\TYPO3\CMS\Extbase\Persistence\ObjectStorage::class);
                foreach ($propertyValue as $subObject) {
                    $subClone = $this->deepcopy($subObject);
                    $objectStorage->attach($subClone);
                }
            } elseif ($propertyValue instanceof \TYPO3\CMS\Extbase\Persistence\Generic\LazyLoadingProxy) {
                $objectStorage = $propertyValue->_loadRealInstance();
            } else {
                $objectStorage = $propertyValue;
            }
            if ($objectStorage !== null) {
                \TYPO3\CMS\Extbase\Reflection\ObjectAccess::setProperty($clone, $propertyName, $objectStorage);
            }
        }

        return $clone;
    }
0

I think a good solution is, to emulate the backend-function. See the code-example (german text) http://blog.marcdesign.ch/2015/05/27/typo3-extbase-objekte-kopieren/

The general idea is to extend the TYPO3\CMS\Core\DataHandling\DataHandler and use the parent-method copyRecord. You declare your predefined backend-user to $this->BE_USER in your extend class. The obejct of your predefined backenduser can you get by using the class TYPO3\\CMS\\Backend\\FrontendBackendUserAuthentication and the known name of you predefined backenduser. Your user should have admin-rights and you should define the $BE_USER->uc_default['copyLevels']= '9999'; and declare $BE_USER->uc = $BE_USER->uc_default. I have not checked, if the declaration $GLOBALS['PAGES_TYPES'][254]['allowedTables'] = '*'; is really needed. The method copyRecorditself needs mainly the table-name, the uid-value, the pid-value and a language-object as parameters.The languages-object can you get $GLOBALS['lang'], which can although be generated by instanciating \TYPO3\CMS\Lang\LanguageService to $GLOBALS['lang'] and \TYPO3\CMS\Core\Charset\CharsetConverter to $GLOBALS['LANG']->csConvObj.

Sorry about my poor english.

3
  • Please find an English version to link to. Also, linked content is not considered part of a StackOverflow answer. Without the link your post is an answer, but maybe not a very detailed one and definitly one without any explanation. Maybe revisit How to Answer. Have fun.
    – Yunnosch
    Jan 20 at 9:03
  • I can't copy foreign content (copyright of the owner). Better than nothing is a link. The main text is the code-example. Use google to translate the text, which has not much informations. If you dislike this answer, give it a thumb down.
    – padina
    Feb 13 at 20:56
  • You cannot copy. You should however summarise what you have linked (not "what" it achieves or describes, but "how" it does so). And no, a link is not better than nothing. Link-only answers routinely get deleted. Please understand that your answer in its current form is evaluated as "emulate the backend-function", and that seems rather brief to me.
    – Yunnosch
    Feb 13 at 22:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.