1

I am having some trouble when trying to create a new Entry in Craft3 via PHP. In Craft 2, I was able to do something like this:

  $entry = new EntryModel();
  $entry->getContent()->title = $name;
  $entry->getContent()->answer = $answer;
  $handle = "nameOfTheSectionIWantToSaveIn";
  $entry->sectionId = craft()->sections->getSectionByHandle($handle)->id;
  $save = craft()->entries->saveEntry($entry);

Before asking, I took some time to read through the Craft3 Class Reference and came across the namespace:

craft\elements

I have come to the conclusion(could be wrong) that I need to use something like the following:

use craft\elements\Entry;
$entry = new Entry();

However, I am a little confused as to where I go from here. I checked the available Craft Entry Public Methods and could not find a method like getContent(), which was used in Craft2. I did see a getContentTable(), but not sure if thats what I am looking for.

| improve this question | | | | |
  • 2
    Please see this craftcms.stackexchange.com/questions/21864/… instead of getContent you just do setFieldValue – Robin Schambach Jun 19 '18 at 4:56
  • that example does not work for me. Instead of saving a matrix field, legit just tried to create an entry with one text field. It fails to save where I check to see if it errors by using $success = Craft::$app->elements->saveElement($entry); then checking if(!$success) { var_dump($success) } . All this returns to me is a bool(false), which doesnt give me much info about what happened. – Dan Zuzevich Jun 22 '18 at 1:32
  • It's impossible to say without your field layout but you can get the reason $entry->getErrors() like in Craft 2 – Robin Schambach Jun 22 '18 at 5:06
  • Thanks guy. By dumping getErrors() in the if conditional, it was able to tell me that my title cannot be blank. Another developer name had changed the default title field to be named, 'journalTitleShort', so I needed to do that inside of setFieldValues. It works. – Dan Zuzevich Jun 22 '18 at 13:35

Your Answer

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

Browse other questions tagged or ask your own question.