<?php
namespace App\EventListener;
use Pimcore\Model\Element\ValidationException;
use Pimcore\Model\DataObject\Distributor;
use Pimcore\Event\Model\ElementEventInterface;
use Pimcore\Event\Model\DataObjectEvent;
class DistributorListener
{
/**
* @param ElementEventInterface $event
*/
public function onPreUpdate(ElementEventInterface $event)
{
if ($event instanceof DataObjectEvent) {
$object = $event->getObject();
if (!$object instanceof Distributor) {
return;
}
// Called to check validation
$this->mandatoryValidation($object);
}
}
/**
* @param ElementEventInterface $event
*/
public function onPreAdd(ElementEventInterface $event)
{
if ($event instanceof DataObjectEvent) {
$object = $event->getObject();
$currentUser = \Pimcore\Tool\Admin::getCurrentUser();
if (!$object instanceof Distributor || $currentUser) {
return;
}
// Called to check validation
$this->mandatoryValidation($object);
}
}
/**
* @param object $object
*/
public function mandatoryValidation($object)
{
$errors = [];
if(empty($object->getName()))
{
$errors[] ='Name is mandatory.';
}
if (!empty($object->getDistributorCode())) {
$distributorCodeUnique = new \Pimcore\Model\DataObject\Distributor\Listing();
if($object->getId()) {
$distributorCodeUnique->setCondition('oo_id !=' . $object->getId() . ' and distributorCode = "' . $object->getDistributorCode() . '"');
} else {
$distributorCodeUnique->setCondition('distributorCode = "' . $object->getDistributorCode() . '"');
}
$distributorCodeUnique->setUnpublished(true);
$distributorCodeUnique->setLimit(1);
$distributorCodeUniqueObject = $distributorCodeUnique->current();
if ($distributorCodeUniqueObject instanceof \Pimcore\Model\DataObject\Distributor && $distributorCodeUniqueObject->getDistributorCode() == $object->getDistributorCode()) {
$errors[] = 'Distributor code already exist in the distributor id ' . $distributorCodeUniqueObject->getId();
}
}
if ($errors) {
throw new ValidationException(implode('<br>', $errors));
}
if (!isset($_GET['task'])) {
return;
}
$errors = [];
if (!empty($object->getDistributorCode())) {
if (strlen($object->getDistributorCode()) < 4) {
$errors[] = 'Distributor code must be more than 3 characters long.';
}
} elseif (empty($object->getDistributorCode())) {
$errors[] = 'Distributor code is mandatory';
}
if ($errors) {
throw new ValidationException(implode('<br>', $errors));
}
}
}