How to remove deleted entry from arraycollection logic in Symfony?

58 views Asked by At

Within a preFlush function in my entity, I have the following code

    $markets = $this->getMarkets();
if(count($this->getAgencies()) > 0){
  foreach($this->getAgencies() as $agency) {
    if(!$this->markets->contains($agency->getMarket())) {
      $this->addMarket($agency->getMarket());
    }
  }
}

so basically what I do, I create documents, which get assigned to agencies and these agencies belong to different markets. Since there are more agencies than markets and I don't want duplicate markets in there, I implemented the if condition. Now adding works perfectly fine. But when I want to edit my document and for example remove an agency from let's say the US (= market) and there is no other agency from the US assigned to the document, I want US to be removed completely from that document. I'm stuck with the logic behind that.

So if the to-be-removed agency/market is not contained within the remaining markets, it should be deleted but if there's still another agency from that market left, the market should (of course) not be deleted.

Markets and Agencies are both ArrayCollections within my document entity, so the removeMarket function exists!

1

There are 1 answers

4
Maxi Schvindt On

For my, with this struct Document -> Agency -> Market

Generate new array $this->markets from Agencies in the preFlush.

OR

Create method getMarkets() and return markets from agencies when you need.