I have 2 entities, Client and Campaign.
Client Entity
/**
* @ORM\OneToMany(targetEntity="Campaign", mappedBy="client")
*/
protected $campaign;
+++++++++++++++++++++++++++++
Campaign Entity
/**
* @var integer
*
* @ORM\Column(name="numberOfBid", type="integer", nullable=true)
*/
protected $numberOfBid;
/**
* @ORM\ManyToOne(targetEntity="Clients", inversedBy="campaign")
* @ORM\JoinColumn(name="client_id", referencedColumnName="client_id")
*/
protected $client;
/* Let's say
Client A has Campaign A, numberOfBid = 1
Client A has Campaign B, numberOfBid = 5
Client A has Campaign C, numberOfBid = 3
Client A has Campaign D, numberOfBid = 4
Total numberofBid = 13
*/
Problem: How do I get the sum of all numberOfBid and show it as 1 column in the Client Admin List Board? On the method configureListFields, I tried different ways like using sonata_type_model, doctrine_orm_callback, query but still didn't work.
Client ID | Campaign TotalBid
A | 13
Hoping for your feedback.
Thanks in advance.
First you should rename your
protected $campaign;
in
protected $campaigns;
cause it's a collection. One client has many campaigns.
To your problem: You could implement a method on your client entity something like this
class Client{
...
public function getTotalNumberOfBids() {
$i = 0;
foreach ($this->getCampaigns() as $campaign) {
$i += $campaign->getNumberOfBid();
}
return $i;
}
...
}
and add to your list view by
protected function configureListFields(ListMapper $list)
{
$list
...
->add('totalNumberOfBids');
}
The "magic getter" will automatic invoke the getTotalNumberOfBids method.
Note: Dependent on the number of objects holding by the campaigns collection, the summation of the numberOfBids could be slow due to the use of the foreach loop.