Problem/Motivation
Adding a constraint of UniqueField to an entity reference field does not enforce that the field value is unique.
One was added by:
function hook_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
if (!empty($fields['field_some_reference'])) {
$fields['field_some_reference']->addConstraint('UniqueField', [
'message' => 'An entity reference %value already exists.'
]);
}
}
Proposed resolution
The problem seems to stem from UniqueFieldValueValidator.php on line 30.
$value_taken = (bool) \Drupal::entityQuery($entity_type_id)
// The id could be NULL, so we cast it to 0 in that case.
->condition($id_key, (int) $items->getEntity()->id(), '<>')
->condition($field_name, $item->value)
->range(0, 1)
->count()
->execute();
$item->value returns nothing for an entity reference field even if a value is present.
Being that it's not the only field type that behaves this way, I am not sure what the best approach is that will cover all field types.
Remaining tasks
Comments
Comment #3
rosk0Lets start form the test.
Comment #5
wengerkThank you for the coverage !
Here is my review:
$bundle&$field- if keep, see my whole global review below- should have a comment explaining what they are. Maybe rename$fieldto$fieldname, which I think is more self more self-explained.\Drupal\user\Entity\Useris never used so could be removed.+use Drupal\user\Entity\User;\Drupal\Core\TypedData\DataDefinitionis never used so could be removed.+use Drupal\Core\TypedData\DataDefinition;More globally, I see that we don't have any tests coverage for UniqueField on Drupal 8. So yours will certainly serve as "base" for the next coverage (if next coverage it has). From this idea, I would suggest 2 things
UniqueFieldEntityReferenceValidatorTest.function testEntityReferenceValidation()What do you think ?
Comment #6
rosk0Added test coverage for most field types from core.
I'm probably missing something about floats by they just don't want to work... Thus commented out.
Test results will clearly show that as soon as field type doesn't have "value" property "UniqueField" constraint doesn't work, e.g. link and entity reference.
The question now is how are we going to solve that? One option is to create a constraint for each such "complex" field type. Another is to check field type in UniqueFieldValueValidator and map to appropriate field property ( which I'm not a fan off ) .
Have no other ideas so open for suggestions.
Comment #7
rosk0Comment #9
wengerkI would suggest to have both new class
UniqueFieldLinkValidator&UniqueFieldEntityValidatorwhat do you think ?IMHO, It would be easier to tests & decoupling is always a better idea than big switch/case for scalability & performance.
Comment #10
rosk0Will work on separate constrains/validators.
Any clues for floats?
Comment #11
rosk0Because of the bug I found in UniqueFieldValueValidator I opened new issue for it #2999225: Unique field constraint does not validated field values on delta greater than 0 and moved test coverage there. I think it would good to deal only with entity reference field in this issue. For the link field type I also opened separate issue #2999226: Unique field constraint does not work with link module fields.
New patch doesn't have confirmation test that UniqueFieldConstraint doen't work for entity reference fields as in comment #6. Not sure if we still need it when we providing new dedicated constraint.
Comment #12
claudiu.cristeaAdded #3027745: UniqueFieldConstraint doesn't work for entities with string IDs as related issue.
Comment #13
wengerkComment #16
andyf commentedI think the snippet in #2999225-22: Unique field constraint does not validated field values on delta greater than 0 might help out for this? (Credit to @joachim in #2999225-20: Unique field constraint does not validated field values on delta greater than 0.)
Comment #17
andyf commentedHere we go... I slightly updated the ER test: it resaved the target rather than the first test entity. I also updated that test so the second constraint was added to the second field, but I noticed that adding the constraint a second time isn't not necessary for the test to pass - I guess it's the same field definition both times?
Thanks!
Comment #19
goldThis is looking good to me. I would RTBC it but there was an outstanding question, and commented out code, around around the floats. In PHP floats, doubles and decimals are all, roughly, the same sort of thing. As I understand it there is an issue of precision between them and the level of precision is also dependant on the underlying OS.
For the purposes of this test I think it's safe to remove the commented out code.
Comment #20
swatichouhan012 commentedComment #21
swatichouhan012 commentedI have removed commented code and updated patch, kindly review.
Comment #22
andyf commentedThanks @swatichouhan012 for pushing this forwards!
I'm looking at those previous failures and it seems to me this constraint shouldn't be used with float types because direct value comparisons on floats entered as decimal will sometimes work and sometimes fail IIUC. I'm not sure if there's some way to enforce that at the code level without explicitly listing compatible field types? At the very least it could do with documentation I reckon.
Comment #23
dunebl@21 working very well, many thank @swatichouhan012
Comment #25
joachim commentedThere's already UniqueFieldConstraintTest -- this seems like it duplicates some of that? Should that existing test be expanded instead?
Does this need to be a class property? It's only used once. Same with the entity type property.
Also, would FieldKernelTestBase::createFieldWithStorage() help with this test?
Comment #26
hardik_patel_12 commented@joachim , Regarding 1st point I have checked there was no UniqueFieldConstraintTest present. For 2nd point $fields , $entityType properties are needed for testing.
@swatichouhan012 i have removed
Declaring ::setUp without a void return typehint in Drupal\KernelTests\Core\TypedData\UniqueFieldValueValidatorTest is deprecated in drupal:9.0.0. Typehinting will be required before drupal:10.0.0. See https://www.drupal.org/node/3114724warning from patch at #21 and also remove some unused key form $filed variable.Comment #27
apugacescu commentedLatest patch does not include the usage of
$main_propertyin violation message parameters, that part still uses 'value'. Attaching an updated patch.Comment #28
alexdmccabeThe same problem was/is happening with link fields, not just entity reference fields. The patch from #27 fixed using the unique field constraint on a link field in Drupal 8.9.1.
I think the root of the problem is that the unique field constraint does not work with any field where the main property name is not "value".
Uploading a new patch rolled against 9.1.x with coding standard fixes for the new test class file.
Comment #33
darvanenStumbled on this and found some time to update the code standards again for 9.3.x.
I think the questions regarding floats, decimals etc is best handled as a follow-up if it is deemed worthy of chasing. By itself this issue improves functionality without addressing that question at all, and as the failure is related to CI configuration rather than this change, I call it RTBC. Time to get some feedback from the core team.
Comment #34
quietone commentedThis has a failing test, setting to NW.
Comment #35
darvanenOh I see, I misread the error message, thanks.
Comment #36
darvanenOk that did the trick. Someone should probably give this another once-over despite the very small changes I made, protocol is protocol.
Comment #37
berdirAdded a few comments and closed #2999226: Unique field constraint does not work with link module fields as a duplicate.
Comment #38
darvanenThis is not a complete job. I can't get the test suite running locally so this is to see if the suggested changes work.
I have a sneaking suspicion that assertCount won't work on $violations. From memory there's more in there than just the list of violations.
Comment #39
darvanenComment #42
murzThanks, this patch works well, thanks! But maybe also add ability to pass custom property to the Constraint manually?
For example to give ability for "Link" field type to make the "Link text" value unique, because mainPropertyName() returns only "uri" field, so users will can use constructions like this:
I've implemented this feature in the separate issue here: https://www.drupal.org/project/drupal/issues/3291483
Comment #44
needs-review-queue-bot commentedThe Needs Review Queue Bot tested this issue. It either no longer applies to Drupal core, or fails the Drupal core commit checks. Therefore, this issue status is now "Needs work".
Apart from a re-roll or rebase, this issue may need more work to address feedback in the issue or MR comments. To progress an issue, incorporate this feedback as part of the process of updating the issue. This helps other contributors to know what is outstanding.
Consult the Drupal Contributor Guide to find step-by-step guides for working with issues.
Comment #45
Akhil Yadav commentedadded patch against #26 in 10.1 version
Comment #46
bramdriesenHiding patch #45 as it's incomplete and omitting a lot of work on tests. The rebase should have happend on the feature branch as well I think in this case.
Adding it to the list here: #3339883: Employees of Dotsquares are posting mass re-roll patches which are invalid and/or incomplete
Comment #47
murzPlease also take a look at my way to resolve this problem in the issue #3291483: Ability to use custom field property in UniqueField constraint.
Comment #49
caesius commentedThis issue should now be resolved by #2478663: UniqueFieldValueValidator works only with single value fields
Comment #50
caesius commentedAlthough some work on tests was done here, it doesn't look like any scenarios were covered that weren't also covered in #2478663: UniqueFieldValueValidator works only with single value fields which resolves the original issue.