I am going to post a solution, this may not be the best performance scenario, but it works and you can further optimize it.
Supposed: AcmeBundle
is your bundle namespace, Product
and Media
are your entities. You need to add a validation for your products, I have used YML, you can change this.
At: AcmeBundle\Resources\config\validation.yml
AcmeBundle\Entity\Product:
constraints:
- Callback: { methods: [validate] }
At: AcmeBundle\Entity\Product
class Product
{
/**
* @var \Doctrine\Common\Collections\Collection
*/
private $media;
[...]
/**
* @param ExecutionContextInterface $context
*/
public function validate(ExecutionContextInterface $context)
{
$allowedPositions = array(1, 2, 3, 4);
foreach ($allowedPositions as $position) {
$atThisPosition = $this->media->filter(function(Media $media) {
return $media->getPosition() === $position;
});
$count = $atThisPosition->count();
if ($count > 1) {
$context->addViolationAt('media', sprintf("Trying to set %d media at position %d", $count, $position));
}
}
}
}