1

I'm trying to create a new Entry via PHP, with custom fields (Craft 3). I can save it, however my custom fields don't appear. I've tried using setFieldValue, as well as $entry->excerpt = 'Lorem...';, however neither work.

My code is below, using craft\elements\Entry:

$entry = new Entry();
$entry->sectionId = 4;
$entry->typeId = 4;
$entry->authorId = 1;
$id = uniqid('product_');
$entry->title = $id;
$entry->slug = $id;

$entry->setFieldValue('excerpt', 'Lorem...');

if(Craft::$app->elements->saveElement($entry)) {
    return $entry;
} else {
    throw new \Exception("Couldn't save new bespoke product: " . print_r($entry->getErrors(), true));
}
2
  • I see you've got this sorted via: github.com/craftcms/cms/issues/1797 Would you mind adding that as an official answer here in case it helps someone in the future?
    – Brad Bell
    Commented Jun 26, 2017 at 21:33
  • No problem, done
    – SteveEdson
    Commented Jun 26, 2017 at 22:20

1 Answer 1

4

It turns out the data wasn't being saved as I hadn't set a fieldLayoutId value.

Now that I've figured this out, I've written a helper method to make saving any entry type much easier:

public static function saveNewEntry(string $handle, array $fields) {

    $entryType = EntryType::find()->where(['handle' => $handle])->one();

    $entry = new Entry();    
    $entry->sectionId = $entryType->getAttribute('sectionId');         
    $entry->typeId = $entryType->getAttribute('id');      
    $entry->fieldLayoutId = $entryType->getAttribute('fieldLayoutId');     
    $entry->authorId = 1; 

    if(isset($fields['title'])) { 
        $entry->title = $fields['title'];     
        unset($fields['title']); 
    }

    if(isset($fields['slug'])) {
        $entry->slug = $fields['slug'];     
        unset($fields['slug']);
    }

    $entry->setFieldValues($fields);

    if(Craft::$app->elements->saveElement($entry)) {
        return $entry;
    } else {
        throw new \Exception("Couldn't save new bespoke product: " . print_r($entry->getErrors(), true)); 
    }
}

This can be used like so:

return self::saveNewEntry('article', [
    'title' => $id,
    'slug' => $id,
    'excerpt' => $excerpt,
    'body' => $body
]);
1
  • Do you know how to save fields of Entries type?
    – biko
    Commented Nov 19, 2019 at 2:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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