Reputation: 243
Situation: I have an form based on an entity. This entity has two properties country and staticRank and the tuple of both these both properties should be unique... BUT: the staticRank could isn't required and due to that, it can be null. I tried solving that problem using the UniqueEntity annotation:
@UniqueEntity(fields={"country", "staticRank"})
This isn't working like expected, because if the staticRank is null it should be a valid combination according to my definition. However, there are several tuples given with the same country and null (for the staticRank), so the constraint notes a violation.
Actual Question: Is there a way to archieve this behaviour without inheriting the "UniqueEntityValidator"?
EDIT: As far as I've experienced, the ignoreNull-property of the constraint would just allow both values to be null (or if the constraint is only set to a single field)
Upvotes: 1
Views: 820
Reputation: 243
Solved that problem by passing a service into my Type (inherited from "AbstractType") and adding a constraint option:
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setRequired('myService');
$resolver->setDefaults([
// ...
'constraints' => [
new Callback([
'callback' => [$this, 'checkCountryRankUniqueness']
])
]
]);
}
In that constraint method, I checked whether the staticRank is null. If it isn't null, it will iterate over all objects and check whether the combination is unique.
Upvotes: 1