How to save a new entry with custom fields - Craft 3 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-&gt;excerpt = 'Lorem...';, however neither work.

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

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

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

if(Craft::$app-&gt;elements-&gt;saveElement($entry)) {
    return $entry;
} else {
    throw new \Exception("Couldn't save new bespoke product: " . print_r($entry-&gt;getErrors(), true));
}
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()-&gt;where(['handle' =&gt; $handle])-&gt;one();

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

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

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

    $entry-&gt;setFieldValues($fields);

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


This can be used like so:

return self::saveNewEntry('article', [
    'title' =&gt; $id,
    'slug' =&gt; $id,
    'excerpt' =&gt; $excerpt,
    'body' =&gt; $body
]);