symfony add unique values from array collection within foreach loop on prepersist

1.2k views Asked by At

I'd like to add 'markets' to my document which can be created within a form where you can select agencies which are assigned to these markets. So you don't specifically select the markets but they are automatically added by selecting the agencies. The logic behind this is working but one thing I didn't yet achieve: there are several agencies for one market, but I only want the markets to be displayed once. My foreach loop looks like that:

if(count($this->getAgencies()) > 0){
  foreach($this->getAgencies() as $agency) {
       $this->addMarket($agency->getMarket());
    }
  }
}

this is working well, as long as I select only one agency per market. As soon as I select several agencies for one market, it's not working anymore. to avoid this, I changed the code to:

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

Since markets and agencies are both arraycollections, a simple "in_Array" or "unique_array" is not working. So I thought "contains" is the function I should use for arraycollections. But apparently it's not.. Any further ideas? :)

1

There are 1 answers

0
T. Abdelmalek On BEST ANSWER

change condition part code, you should check if market for agency already exists in $this->markets collections:

if(!$this->markets->contains($agency->getMarket())) {
      $this->addMarket($agency->getMarket());
}