Skip to content
Advertisement

Clone entity and all related entities in CakePHP 3

In my CakePHP 3 app, I have a somewhat elaborate tree of entities that I need to clone and save.

The root of the structure is a Questionnaire, a Questionnaire hasMany Questions, each Question hasMany Fields, etc. (it goes deeper). Now I want the user to be able to define a new questionnaire by copying an old one. Then they can change whatever they need.

I can get a dump of what I need to copy by using $questionnaire->$this->Questionnaires->get($id) with the appropriate contain fields. Is there a clever way to save this as a bunch of new entities while preserving the data and the structure between them?

Advertisement

Answer

I think the best possible way would be following work flow:

  1. Get object you want to clone
  2. Go through the collection and remove all ID’s
  3. Convert to array and use that in $this->Questionnaires->newEntity($arrayData, ['associated' => ['Questions', '...']]);
  4. Now save the new entity with all the related data you want to keep

AFAIK there’s no “smarter” way of cloning an entity with associations in Cake 3 🙂

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement