1

I'm trying to save an entry via a controller. They are contact form submission. A few of the fields are required.

    $section = Craft::$app->sections->getSectionByHandle('contactSubmissions');

    $entry = new Entry();
    $entry->sectionId = $section->id;
    $entry->typeId = 2;
    $entry->authorId = 1;
    $entry->enabled = true;

    $entry->setFieldValues([
        'contactName' => ucwords($data['contactName']),
        'contactEmail' => $data['contactEmail'],
        'contactCompany' => $data['contactCompany'],
        'contactMessage' => $data['contactMessage'],
        'contactHeardAbout' => $data['contactHeardAbout'],
        'contactWebsite' => $data['contactWebsite'],
        'contactTitle' => $data['contactTitle'],
    ]);

    
    if ( Craft::$app->elements->saveElement($entry) ) {
        //$this->sendMail($entry);
    }
    
    die(var_dump($entry->getErrors()));

    return $entry;

The only validation that runs if the missing title, which in this case is the contactName. All other keys in the $data array are empty strings. They do not trigger any validation and the empty entry saves into the database.

If I were to go into the control panel and try to save the entry, it would fail with the validation errors.

If I were to enter a value for the email field, but have an invalid email, that validation then gets triggered. But none of the empty fields do.


Additional info

Craft version: 3.6.10

PHP version: 7.3.13

1 Answer 1

2

You would need to set the entry's scenario to live just before saving the element.

$section = Craft::$app->sections->getSectionByHandle('contactSubmissions');

$entry = new Entry();
$entry->sectionId = $section->id;
$entry->typeId = 2;
$entry->authorId = 1;
$entry->enabled = true;

$entry->setFieldValues([
    'contactName' => ucwords($data['contactName']),
    'contactEmail' => $data['contactEmail'],
    'contactCompany' => $data['contactCompany'],
    'contactMessage' => $data['contactMessage'],
    'contactHeardAbout' => $data['contactHeardAbout'],
    'contactWebsite' => $data['contactWebsite'],
    'contactTitle' => $data['contactTitle'],
]);

$entry->setScenario(Entry::SCENARIO_LIVE);

if ( Craft::$app->elements->saveElement($entry) ) {
    //$this->sendMail($entry);
}

die(var_dump($entry->getErrors()));

return $entry;

Alternatively, If you want to save entries from the front-end, unless you have very specific requirements, you could use:

1
  • Thank you and Brandon for this! I wouldn't have been able to figure out this one Commented Mar 31, 2021 at 13:21

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.