0

I have a Content Type with a field that references 6 different paragraph types. The field is set up to accept unlimited values. For one of the types I would like to have exactly four values added. I've been trying to add a Constraint but it seems that Constraints are built to check if a fields values are valid and not if there are only four items

Is using hook_entity_bundle_field_info_alter the correct hook or should I be focused on using hook_entity_type_alter or maybe even some other method?

3

Yes, use hook_entity_bundle_field_info_alter and when you add a constraint to the field (and not to a item or property), your constraint gets the entire field item list, so you can check how many items you have of which type, see FieldConfigInterface::addConstraint:

function mymodule_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() == 'node' && $bundle == 'page') {
    $fields['field_paragraph']->addConstraint('MymoduleParagraphTypes');
  }
}

Example for a constraint restricting the field to four paragraph items of a specific type:

  public function validate($items, Constraint $constraint) {
    $paragraphs = array_filter($items->referencedEntities(), function ($paragraph) {
      return $paragraph->bundle() === 'image';
    });
    if (!empty($paragraphs) && count($paragraphs) != 4) {
      $this->context->addViolation($constraint->errorMessage);
    }
  }

You can generate the constraint with the Drush command:

drush generate plugin-constraint
  • This seems like what I want. I keep getting plugin Instance class does not exist though. – StevenPatz Mar 23 at 2:01
  • Try the drush generate command. In this example the constraint ID was MymoduleParagraphTypes, which you find in the first class generated. Then put the example code in the second class. – 4k4 Mar 23 at 9:12
  • Starting fresh got the weird errors to go away. Marked your answer. Counting is a bit off though. I want four and it is only finding ine – StevenPatz Mar 25 at 16:00
  • It seems like the code is only counting the number of paragraphs on the edit page and not the number of entities in that paragraph. If I do count ($items->$referencedEntities()) it always returns one no matter how many I've added – StevenPatz Mar 25 at 17:41
  • I've tested this on a field accepting different paragraphs types and it worked. I had to add exactly four Image paragraphs once I've started to add an Image paragraph. Therefor the empty condition, so you could use the field for the other types without adding images. – 4k4 Mar 25 at 17:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.