Is there an simple cakephp way to duplicate an article/table row in the same table ?
By simple, I mean, of course, not having to list all fields and copy them one by one just like you would do in pure php ? (which is easy but not so straightforward)
Or just clear the ID and reset isNew
to true?
Or create a new entity from $oldEntity->toArray()
, making sure that the ID is not an accessible field?
Thank you all.
I will try those ideas and let you know.
Very easy in fact !
public function duplicate($id)
{
$article = $this->Articles->get($id);
$newArticle = $this->Articles->newEntity();
$this->request->data = $article->toArray();
$this->request->data['name'] = $article->name . " - " . __("copy");
$this->request->data['slug'] = $article->slug . "-" . __("copy");
$newArticle = $this->Articles->patchEntity($newArticle, $this->request->data);
if ($this->Articles->save($newArticle)) {
$this->Flash->success(__('The article has been duplicated.'));
return $this->redirect(['controller' => 'articles', 'action' => 'edit', $newArticle->id]);
} else {
$this->Flash->error(__('The article could not be duplicated. Please, try again.'));
}
}
Thank you for showing me the way.
(Did not try the plugin but I keep the link so I can try it later)
you can straight away save it and don’t need to add the extra step of patchEntity
$newArticle = $this->Articles->newEntity( $this->Articles->get($id)->toArray() );
$newArticle->id = null; // unset id to be safe
$newArticle->setNew(true); // setting entity to new, for safety
$newArticle->name = $newArticle->name . " - " . __("copy");
$newArticle->slug = $newArticle->slug . " - " . __("copy");
$this->Articles->save( $newArticle );
Simpler of course.
But as long as you call newEntity() do we really need $newArticle->id = null; and $newArticle->setNew(true); ?
You need id = null assuming you have auto_increment primary key in your db, if you don’t you must assign new id manually. Probably you don’t need isNew() when using newEntity. Just debug($newArticle)
before newEntity()
line and check it out.
you can also use php clone:
$source; //your original from somewhere
$new = clone($source);
$new->id = null;
$new->isNew(true);
`
Thank you all for showing different ways !