Skip to content

Instantly share code, notes, and snippets.

@leowebguy
Created January 26, 2021 23:10
Show Gist options
  • Save leowebguy/2b00d9313cea1a9785af69e61105697f to your computer and use it in GitHub Desktop.
Save leowebguy/2b00d9313cea1a9785af69e61105697f to your computer and use it in GitHub Desktop.
Craft 3 Entry Field Type Validation
<?php
/**
* Craft 3 Entry Validation
*
* This goes in the main plugin class.
*
* Event::on(
* Entry::class,
* Entry::EVENT_BEFORE_SAVE,
* function (ModelEvent $event) {
* if (!$event->isNew) { // prevent new entry/draft error
* PluginName::$plugin->validateService->validateEntry($event);
* }
* }
* );
*/
namespace ns\plugin\services;
use Craft;
use craft\base\Component;
use craft\elements\Entry;
class ValidateService extends Component
{
public function validateEntry($event)
{
$sender = $event->sender;
$handle = $sender->section->handle;
if ($handle == 'sessionName') {
foreach ($sender->fieldName->all() as $entryField) {
$entry = Entry::findOne($fieldName->id);
if (empty($entry->textField)) { // text
$sender->addError('fieldName', Craft::t('pluginName', $entry->title . ' must have a value for field1.'));
return $event->isValid = false;
}
if (count($entry->assetField) == 0) { // asset
$sender->addError('fieldName', Craft::t('pluginName', $entry->title . ' must have at least one asset in field2.'));
return $event->isValid = false;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment