0

How can I create a plugin that will let me copy entry?

I found this question but don't have a good answer.

  • 1
    You specifically want to do it programmatically from a plugin and not from the control panel, correct? – Brad Bell Oct 16 '15 at 22:49
3

You’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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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