监听model:beforeValidationOnCreate事件

@param Event $event
@param Model $model
12449
public function beforeValidationOnCreate(Event $event, Model $model)
    {
        if ($model instanceof ISequenceSubject) {
            $type = $model->getSequenceType();
            //查找服务
            $generatorName = $this->getDi()->get('config')->get('model.sequence.' . $type);
            if (!$generatorName) {
                throw new NonExistingGeneratorException($generatorName);
            }

            /** @var IGenerator $generator */
            $generator = $this->getDi()->get($generatorName);

            $model->setNumber($generator->generate($model));
        }
    }
240035
public function beforeDelete($event)
    {
        $oldId = $this->owner->{$this->savedAttribute};
        if (($oldModel = FileModel::findOne($oldId)) !== null) {
            $event->isValid = $event->isValid && $oldModel->delete();
        }
    }
531968
public function beforeUpdate($event)
    {
        $fields = $this->fields;
        $nowDate = gmdate($this->databaseTimeFormat);
        if (!$this->isActuallyDirty()) {
            return;
        }

        if (isset($this->fields['modifiedField']) && !$this->owner->isAttributeChanged($this->fields['modifiedField'])) {
            $this->owner->{$this->fields['modifiedField']} = $nowDate;
        }
        if (isset($this->fields['modifiedByField']) && !$this->owner->isAttributeChanged($this->fields['modifiedByField'])) {
            $this->owner->{$this->fields['modifiedByField']} = self::_getUserId();
        }
    }
371917
protected function insertModelBeforeElement(Model &$model, Model &$element)
    {
        if ($element->isNew())
            throw new Exception('Target model should be saved before insert');

        $element->refreshTreeColumns();

        /** @var \T4\Orm\Model $class */
        $class = get_class($model);
        $tableName = $class::getTableName();
        /** @var \T4\Dbal\Connection $connection */
        $connection = $class::getDbConnection();

        $this->expandTreeBeforeElement($element, $model->getTreeWidth());

        if (!$model->isNew()) {

            $model->refreshTreeColumns();
            $diff = $element->__lft - $model->__lft;
            $lvldiff = $element->__lvl - $model->__lvl;

            $query = (new Query())
                ->update()
                ->table($tableName)
                ->values([
                    '__lft' => '__lft + :diff',
                    '__rgt' => '__rgt + :diff',
                    '__lvl' => '__lvl + :lvldiff',
                    '__prt' => 'CASE WHEN __id=:id THEN :parentid ELSE __prt END',
                ])
                ->where('__lft>=:lft AND __rgt<=:rgt')
                ->params([':id' => $model->getPk(), 'parentid'=>$element->__prt, ':lft' => $model->__lft, ':rgt' => $model->__rgt, ':diff' => $diff, ':lvldiff' => $lvldiff]);
            $connection->execute($query);

            $this->removeFromTreeByElement($model);

        } else {
            // TODO: этот вариант тоже рассмотреть
            throw new Exception('Save this model before move');
        }

        // TODO: рассчитывать
        $model->refreshTreeColumns();
        $element->refreshTreeColumns();

    }
416985
public function beforeSave(Event $event, Entity $entity) {
        if(!$entity->get('slug') || $this->_config['overwrite'])
            $entity->set('slug', $this->slug($entity->get($this->_config['field'])));
    }
503436
public function model(ModelEvent $event)
    {
        if (isset($this->logger)) {
            $operation = get_class($event);

            $model = $event->getModel();

            $on = get_class($model);

            $connection = $model->getQuery()->getConnection();

            $message = "LDAP ({$connection->getHost()})"
                . " - Connection: {$connection->getName()}"
                . " - Operation: {$operation}"
                . " - On: {$on}"
                . " - Distinguished Name: {$model->getDn()}";

            $this->logger->info($message);
        }
    }
438884
public function beforePrepare(Event $event)
	{
		$command = $event['command'];
		$operation = $command->getOperation();
		$client = $command->getClient();

		if ($command->getName() !== 'updateEntity') return;
		if ($operation->getParam('collection')->getDefault() !== 'user') return;

		// Attempt to get the model's deleted at value from the array of values passed
		// to the command.
		$statusValue = false;

		if ($command->offsetExists(Model::DELETED_AT))
		{
			$statusValue = $command->offsetGet(Model::DELETED_AT);
		}
		elseif ($command->offsetExists('_kmd'))
		{
			$_kmd = array_dot($command->offsetGet('_kmd'));

			$statusField = MODEL::DELETED_AT;
			$statusField = str_replace('_kmd.', '', MODEL::DELETED_AT);

			if (array_key_exists($statusField, $_kmd))
			{
				$statusValue = $_kmd[$statusField];
			}
		}

		// Could not determine the status field.
		if ($statusValue === false)
		{
			return;
		}
		// Suspend the user.
		elseif (!is_null($statusValue))
		{
			$event->stopPropagation();

			$suspendCommand = $client->getCommand('deleteEntity', array(
				'collection' => 'user',
				'_id' => $command->offsetGet('_id'),
			));
			$suspendCommand->execute();
		}
		// Restore.
		else
		{
			$event->stopPropagation();

			$restoreCommand = $client->getCommand('restore', array(
				'_id' => $command->offsetGet('_id'),
			));
			$restoreCommand->execute();
		}
	}
845048
public function beforeRender(Event $event)
    {
        if (!Configure::read('debug')) {
            return;
        }

        $this->_action()->setConfig('serialize.queryLog', 'queryLog');
        $this->_controller()->set('queryLog', $this->_getQueryLogs());
    }
381785
public function beforeFilter(Event $event)
    {
        $this->viewBuilder()->className(Configure::read('CA.viewClass'))->theme(Configure::read('CA.theme'));

        if ($this->authUser) {
            $this->viewBuilder()->layout(Configure::read('CA.layout.default'));
        } else {
            $this->viewBuilder()->layout(Configure::read('CA.layout.login'));
        }

        $this->_addNotificationMenu();

        $event = new Event('CakeAdmin.Controller.beforeFilter', $this);
        EventManager::instance()->dispatch($event);
    }
558319
public function afterValidate(Model $model) {
		if (!empty($model->validationErrors)){
			$model->data[$model->alias] = $this->runtime[$model->alias]['data'];
		}
		
		return true;
	}
867431
public function beforeDeleteTree(Event $event)
    {
        if ($children = $this->getChildren()->all()) {
            foreach ($children as $childNode) {
                $childNode->delete();
            }
        }
    }
167806
public function validate(FormEvent $event)
    {
        /** @var Alias $alias */
        $alias = $event->getData()->getNode()->alias;

        if ($alias instanceof ValueHolderInterface) {
            $alias = $alias->getWrappedValueHolderValue();
        }

        $violations = $this->validator->validate($alias);

        if (!$violations) {
            return;
        }

        $mapper = new ViolationMapper();
        /** @var ConstraintViolationInterface $violation */
        foreach ($violations as $violation) {
            $mapper->mapViolation($violation, $event->getForm(), true);
        }
    }
504187
public function preCreate(CreateEvent $event)
    {
        $subject = $event->getObject();
        $forum = $subject->getForum();

        //create user if not here
        $user = $this->om->getRepository('ClarolineForumBundle:Validation\User')->findOneBy([
          'user' => $subject->getCreator(),
          'forum' => $forum,
        ]);

        if (!$user) {
            $user = new User();
            $user->setForum($forum);
            $user->setUser($subject->getCreator());
        }

        $messages = $subject->getMessages();
        $first = $messages && isset($messages[0]) ? $messages[0] : null;

        if (!$this->checkPermission('EDIT', $forum->getResourceNode())) {
            if (Forum::VALIDATE_PRIOR_ALL === $forum->getValidationMode()) {
                $subject->setModerated(Forum::VALIDATE_PRIOR_ALL);
                if ($first) {
                    $first->setModerated(Forum::VALIDATE_PRIOR_ALL);
                }
            }

            if (Forum::VALIDATE_PRIOR_ONCE === $forum->getValidationMode()) {
                $subject->setModerated($user->getAccess() ? Forum::VALIDATE_NONE : Forum::VALIDATE_PRIOR_ONCE);
                if ($first) {
                    $first->setModerated(Forum::VALIDATE_PRIOR_ALL);
                }
            }
        } else {
            $subject->setModerated(Forum::VALIDATE_NONE);
            if ($first) {
                $first->setModerated(Forum::VALIDATE_PRIOR_ALL);
            }
        }

        if ($first) {
            $this->om->persist($first);
        }

        return $subject;
    }
918334
public function beforeRender(Event $event) {
		if (in_array('Captcha.Captcha', $this->controller->helpers) || isset($this->controller->helpers['Captcha.Captcha'])) {
			return;
		}

		$this->controller->helpers[] = 'Captcha.Captcha';
	}
124200
public function beforeRender(Event $event) {
		/** @var \Cake\Controller\Controller $controller */
		$controller = $event->getSubject();
		$controller->viewBuilder()->setClassName($this->_config['viewClass']);

		// Set flash messages to the view
		if ($this->_config['flashKey']) {
			$message = $controller->getRequest()->getSession()->consume($this->_config['flashKey']);
			if ($message || !array_key_exists('_message', $controller->viewVars)) {
				$controller->set('_message', $message);
			}
		}

		// If _serialize is true, *all* viewVars will be serialized; no need to add _message.
		if ($this->_isSerializeTrue($controller)) {
			return;
		}

		$serializeKeys = ['_message'];
		if (!empty($controller->viewVars['_serialize'])) {
			$serializeKeys = array_merge((array)$controller->viewVars['_serialize'], $serializeKeys);
		}
		$controller->set('_serialize', $serializeKeys);
	}
494338
public function beforeRender(Event $event)
    {
        $request = $this->_request();

        if (empty($request->getParam('paging'))) {
            return;
        }

        $controller = $this->_controller();

        list(, $modelClass) = pluginSplit($controller->modelClass);

        if (!array_key_exists($modelClass, $request->getParam('paging'))) {
            return;
        }

        $pagination = $request->getParam('paging')[$modelClass];
        if (empty($pagination)) {
            return;
        }

        $controller->set('_pagination', $this->_getJsonApiPaginationResponse($pagination));
    }
1282496
public static function isValidNextStatus($model, $status_id)
	{
		$eventSequence = $model->getEventSequence($status_id);
		foreach ($eventSequence['before'] as $event) {
			if ($model->hasEventHandlers($event->name)) {
				$model->trigger($event->name, $event);
				if ($event->isValid === false) {
					return false;
				}
			}
		}
		return true;
	}