sonja
sonja

Reputation: 934

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

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? :)

Upvotes: 0

Views: 1374

Answers (1)

T. Abdelmalek
T. Abdelmalek

Reputation: 428

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());
}

Upvotes: 2

Related Questions