How can I create a plugin that will let me copy entry?
I found this question but don't have a good answer.
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It only takes a minute to sign up.
Sign up to join this communityYou’d start by creating a new EntryModel and copying over the normal properties:
$oldEntry = craft()->entries->getEntryById(100);
$newEntry = new EntryModel();
// core element attributes
$newEntry->enabled = $oldEntry->enabled;
$newEntry->locale = $oldEntry->locale;
$newEntry->localeEnabled = $oldEntry->localeEnabled;
$newEntry->slug = $oldEntry->slug;
$newEntry->uri = $oldEntry->uri;
$newEntry->getContent()->title = $oldEntry->getContent()->title;
// entry attributes
$newEntry->sectionId = $oldEntry->sectionId;
$newEntry->typeId = $oldEntry->typeId;
$newEntry->authorId = $oldEntry->authorId;
$newEntry->postDate = $oldEntry->postDate;
$newEntry->expiryDate = $oldEntry->expiryDate;
// do this if it's in a Structure section
if (($parent = $oldEntry->getParent()) !== null)
{
$newEntry->parentId = $parent->id;
}
Where things get tricky is copying all of the content. That's tough because many field types expect their values to be in one format when saving, but they return their values in another format when you call $entry->myFieldHandle
. For example relationship fields (Entries, Assets, Users, Categories, and Tags) each expect you to set their values as an array of related elements’ IDs when saving an entry, but when you call $entry->myRelationalField
(or entry.myRelationalField
from a template) you’re getting an ElementCriteriaModel back. So for those, you’d have to do this:
$newEntry->setContentFromPost(array(
'myAssetsField' => $oldEntry->myAssetsField->ids()
));
There are some other posts that touch on how to format the various field types’ values (i.e. Duplicating Matrix fields with content from another locale), but nothing comprehensive.