1

I am currently trying to save a new entry with craft()->elements->saveElement(), as I want to avoid triggering the onBeforeSave and onAfterSave events.

When I run my script, it returns a successful entry id, but there is no entry in the admin.

Here is my code:

$entry = new EntryModel();
$entry->sectionId = $sectionId;
$entry->typeId = $entryTypeId;
$entry->enabled = true;
$entry->authorId = 1;

$success = craft()->elements->saveElement($entry, false);

if ($success) {
    echo $entry->id;
}
  • Not an answer, but check out Craft's own craft/app/controllers/EntriesController->saveEntry() to see how an EntryModel is created and populated and passed off to the ElementsService. – Brad Bell Mar 7 '18 at 3:14
  • Thanks! I've done a little digging there but haven't quite figured out what might be missing. I'll keep digging. – Alex Glover Mar 7 '18 at 20:38
  • @BradBell I ended up copying the saveEntry method from the EntriesService and ripping out anything event related. Additionally, I think it'd be amazing if there were a way to call saveEntry and disable any events, although I don't know if that would ever be possible. – Alex Glover Mar 8 '18 at 14:22
  • You can do that by simply create a new instance of the entries service I noticed that by mistake craftcms.stackexchange.com/questions/19334/… – Robin Schambach Mar 8 '18 at 22:44
2

In Craft's v3 API documentation they give an example:

https://docs.craftcms.com/api/v3/craft-services-elements.html#method-saveelement

$entry = new Entry();
$entry->sectionId = 10;
$entry->typeId = 1;
$entry->authorId = 5;
$entry->enabled = true;
$entry->title = "Hello World!";
$entry->setFieldValues([
    'body' => "<p>I can’t believe I literally just called this “Hello World!”.</p>",
]);
$success = Craft::$app->elements->saveElement($entry);
if (!$success) {
    Craft::error('Couldn’t save the entry "'.$entry->title.'"', __METHOD__);
}
  • Just FYI, this is not the question I was asking above if you will notice. I was asking how to prevent re-triggering the onBeforeSave and onAfterSave if I create entries programmatically. – Alex Glover May 15 '19 at 13:05

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.