C
C
coderisimo2020-09-15 09:24:05
symfony
coderisimo, 2020-09-15 09:24:05

How to get changes in single associations in onFlush in doctrine event listener?

For the third time he threw a net)).
Through research, I found that if I want to save something new (for example, entity change log) in doctrine event listener , then I have to do it in onFlush using $unitOfWork->computeChangeSet...But

I can get added and removed in onFlush entities. I can get in onFlush collection of associations. But I absolutely do not understand how to get SINGLE ASSOCIATIONS there (or rather, their changes). It would seem that if there is the first and second, then the third should be available, but xxxxxx.......

In other words, I need in onFlush what is in preUpdate - PreUpdateEventArgs. Saving something in preUpdate is strongly discouraged and does not work. It turns out an interesting situation: I can
save the log in onFlush, but the required information is not there. I cannot
save the log in preUpdate , although everything I need is there. I will be grateful for advice. Thanks

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
coderisimo, 2020-09-15
@coderisimo

I will write here so that there is an answer that may save someone else time and NEVRA.
Thank you BoShurik !!!! see topic for details.
Simple associations are available in onFlush via
$unitOfWork->getEntityChangeSet($entity);
next

$metaData = $entityManager->getClassMetadata(get_class($entity));
            //отбираем ассоциации "не коллекции" и только изменненные.
            $singleAssociations = array_filter($metaData->getAssociationNames(), function ($association) use ($metaData) {
                return $metaData->isSingleValuedAssociation($association);
            });

            $data = [];
            foreach ($changesSet as $key => $field) {
                if (in_array($key, $singleAssociations)) {
// где $field[0] и $field[1] будут как раз простыми ассоциациями "до" и "после"
//getAssocFieldValue - просто метод который берет из ассоциации нужное простое значение для  лога
                    $data[$key] = [$this->getAssocFieldValue($field[0]), $this->getAssocFieldValue($field[1])];
                } 
            }

A
Anton, 2020-09-15
@sHinE

I don't think it was exactly the same situation, but a similar one.
One class is created that implements EventSubscriber and it contains two methods that you need (preUpdate and onFlush ).
In your case, in preUpdate you save the data that you need to save to the class property, and already in onFlush you read it from this property and save it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question