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

Issue fork drupal-2973455

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

mstef created an issue. See original summary.

Version: 8.5.x-dev » 8.6.x-dev

Drupal 8.5.6 was released on August 1, 2018 and is the final bugfix release for the Drupal 8.5.x series. Drupal 8.5.x will not receive any further development aside from security fixes. Sites should prepare to update to 8.6.0 on September 5, 2018. (Drupal 8.6.0-rc1 is available for testing.)

Bug reports should be targeted against the 8.6.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.7.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

rosk0’s picture

Version: 8.6.x-dev » 8.7.x-dev
Status: Active » Needs review
StatusFileSize
new3.25 KB

Lets start form the test.

Status: Needs review » Needs work

The last submitted patch, 3: 2973455-3.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

wengerk’s picture

Thank you for the coverage !

Here is my review:

  • - both protected $bundle & $field - if keep, see my whole global review below- should have a comment explaining what they are. Maybe rename $field to $fieldname, which I think is more self more self-explained.
    +  protected $bundle = 'reference';
    +  protected $field = 'field_reference';
  • - \Drupal\user\Entity\User is never used so could be removed.
    +use Drupal\user\Entity\User;
  • - \Drupal\Core\TypedData\DataDefinition is 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

  • - Renaming this class as it only coverage Entity Reference field - something like UniqueFieldEntityReferenceValidatorTest .
  • OR
  • - Renaming the coverage to reflect it only cover Entity Reference field - something like function testEntityReferenceValidation()

What do you think ?

rosk0’s picture

StatusFileSize
new8.13 KB

Added 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.

rosk0’s picture

Status: Needs work » Needs review

Status: Needs review » Needs work

The last submitted patch, 6: 2973455-6.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

wengerk’s picture

I would suggest to have both new class UniqueFieldLinkValidator & UniqueFieldEntityValidator what do you think ?

IMHO, It would be easier to tests & decoupling is always a better idea than big switch/case for scalability & performance.

rosk0’s picture

Assigned: Unassigned » rosk0

Will work on separate constrains/validators.

Any clues for floats?

rosk0’s picture

Assigned: rosk0 » Unassigned
Status: Needs work » Needs review

Because 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.

claudiu.cristea’s picture

Version: 8.7.x-dev » 8.8.x-dev

Drupal 8.7.0-alpha1 will be released the week of March 11, 2019, which means new developments and disruptive changes should now be targeted against the 8.8.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.8.x-dev » 8.9.x-dev

Drupal 8.8.0-alpha1 will be released the week of October 14th, 2019, which means new developments and disruptive changes should now be targeted against the 8.9.x-dev branch. (Any changes to 8.9.x will also be committed to 9.0.x in preparation for Drupal 9’s release, but some changes like significant feature additions will be deferred to 9.1.x.). For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

andyf’s picture

StatusFileSize
new8.12 KB
new8.93 KB
new1.52 KB

Here 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!

The last submitted patch, 17: 2973455-17--FAIL.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

gold’s picture

Status: Needs review » Needs work

This 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.

swatichouhan012’s picture

Assigned: Unassigned » swatichouhan012
swatichouhan012’s picture

Assigned: swatichouhan012 » Unassigned
Status: Needs work » Needs review
StatusFileSize
new8.87 KB
new566 bytes

I have removed commented code and updated patch, kindly review.

andyf’s picture

Thanks @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.

dunebl’s picture

@21 working very well, many thank @swatichouhan012

Version: 8.9.x-dev » 9.1.x-dev

Drupal 8.9.0-beta1 was released on March 20, 2020. 8.9.x is the final, long-term support (LTS) minor release of Drupal 8, which means new developments and disruptive changes should now be targeted against the 9.1.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

joachim’s picture

Status: Needs review » Needs work
  1. +++ b/core/tests/Drupal/KernelTests/Core/TypedData/UniqueFieldValueValidatorTest.php
    @@ -0,0 +1,249 @@
    +class UniqueFieldValueValidatorTest extends EntityKernelTestBase {
    

    There's already UniqueFieldConstraintTest -- this seems like it duplicates some of that? Should that existing test be expanded instead?

  2. +++ b/core/tests/Drupal/KernelTests/Core/TypedData/UniqueFieldValueValidatorTest.php
    @@ -0,0 +1,249 @@
    +  protected $fields = [
    

    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?

hardik_patel_12’s picture

Status: Needs work » Needs review
StatusFileSize
new8.78 KB
new344 bytes

@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 removedDeclaring ::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/3114724 warning from patch at #21 and also remove some unused key form $filed variable.

apugacescu’s picture

StatusFileSize
new9.11 KB
new741 bytes

Latest patch does not include the usage of $main_property in violation message parameters, that part still uses 'value'. Attaching an updated patch.

alexdmccabe’s picture

Title: Unique field constraint does not work with entity reference fields » Unique field constraint does not work with any field main property name that is not "value"
StatusFileSize
new9.21 KB
new1.02 KB

The 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.

Version: 9.1.x-dev » 9.2.x-dev

Drupal 9.1.0-alpha1 will be released the week of October 19, 2020, which means new developments and disruptive changes should now be targeted for the 9.2.x-dev branch. For more information see the Drupal 9 minor version schedule and the Allowed changes during the Drupal 9 release cycle.

Version: 9.2.x-dev » 9.3.x-dev

Drupal 9.2.0-alpha1 will be released the week of May 3, 2021, which means new developments and disruptive changes should now be targeted for the 9.3.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Darvanen made their first commit to this issue’s fork.

darvanen’s picture

Status: Needs review » Reviewed & tested by the community

Stumbled 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.

quietone’s picture

Status: Reviewed & tested by the community » Needs work

This has a failing test, setting to NW.

darvanen’s picture

Oh I see, I misread the error message, thanks.

darvanen’s picture

Status: Needs work » Needs review

Ok that did the trick. Someone should probably give this another once-over despite the very small changes I made, protocol is protocol.

berdir’s picture

Status: Needs review » Needs work

Added a few comments and closed #2999226: Unique field constraint does not work with link module fields as a duplicate.

darvanen’s picture

This 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.

darvanen’s picture

Status: Needs work » Needs review

Version: 9.3.x-dev » 9.4.x-dev

Drupal 9.3.0-rc1 was released on November 26, 2021, which means new developments and disruptive changes should now be targeted for the 9.4.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 9.4.x-dev » 9.5.x-dev

Drupal 9.4.0-alpha1 was released on May 6, 2022, which means new developments and disruptive changes should now be targeted for the 9.5.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

murz’s picture

Thanks, 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:

      $fields['link']->addConstraint('UniqueField', [
        'property' => 'title',
      ]);

I've implemented this feature in the separate issue here: https://www.drupal.org/project/drupal/issues/3291483

Version: 9.5.x-dev » 10.1.x-dev

Drupal 9.5.0-beta2 and Drupal 10.0.0-beta2 were released on September 29, 2022, which means new developments and disruptive changes should now be targeted for the 10.1.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

needs-review-queue-bot’s picture

Status: Needs review » Needs work
StatusFileSize
new149 bytes

The 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.

Akhil Yadav’s picture

StatusFileSize
new834 bytes

added patch against #26 in 10.1 version

bramdriesen’s picture

Hiding 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

murz’s picture

Version: 10.1.x-dev » 11.x-dev

Drupal core is moving towards using a “main” branch. As an interim step, a new 11.x branch has been opened, as Drupal.org infrastructure cannot currently fully support a branch named main. New developments and disruptive changes should now be targeted for the 11.x branch, which currently accepts only minor-version allowed changes. For more information, see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

caesius’s picture

caesius’s picture

Status: Needs work » Closed (duplicate)

Although 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.