Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 207
XerXes Avatar asked Nov 10 '15 15:11

XerXes


2 Answers

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 :-)

like image 129
Spriz Avatar answered Sep 20 '22 18:09

Spriz


You could also use this plugin. You only have to configure the behavior and it gives you other functionalities, like setting default values or appending text to some field.

like image 26
pperejon Avatar answered Sep 19 '22 18:09

pperejon