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

good_afternoon
  • 319
  • 1
  • 10

1 Answers1

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:

Oli
  • 7,495
  • 9
  • 17