Problem/Motivation

In some case we want to limit unique value within the bundle of the specific entity type. Example like this https://www.drupal.org/docs/drupal-apis/entity-api/entity-validation-api... or the one in the description of #2973455: Unique field constraint does not work with any field main property name that is not "value" make it feel like it is possible, but UniqueField constraint doesn't support it.

One could even argue that this is a bug, but that is not so important.

Steps to reproduce

  • Add the UniqueField constraint to a specific bundle field with something like:
    /**
       * Prevent duplicated in my_bundle.
       */
      #[Hook('entity_bundle_field_info_alter')]
      public function uniqueBundleField(&$fields, EntityTypeInterface $entity_type, $bundle) {
    
        $field_name = 'field_name';
        if (isset($fields[$field_name])) {
          $fields[$field_name]->addConstraint('UniqueField', []);
        }
        if ($entity_type->id() === 'entity_type' && $bundle === 'my_bundle') {
          if (isset($fields[$field_name])) {
            $fields[$field_name]->addConstraint('UniqueField', []);
          }
        }
      }
    
  • create an entity of "entity_type" and bundle other than "my_bundle" with the "field_name" value of "field_value"
  • create an entity of "entity_type" and bundle "my_bundle" with the "field_name" value of "field_value"
  • observe the duplicated error message

Proposed resolution

Add support for limiting duplicates check within a configured bundle

Remaining tasks

implement
review
commit

API changes

Addition of the bundle configuration option to the UniqueFieldConstraint

Release notes snippet

TBD

Issue fork drupal-3597942

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

rosk0 created an issue. See original summary.

rosk0’s picture

Status: Active » Needs review

Bundle support added. Tests added. Please review

rosk0’s picture

Added separate merge request targeting 11.x as this is where I need this at present.

https://git.drupalcode.org/project/drupal/-/merge_requests/16646