0

I have a custom field defined in a module I am writing and it works correctly; but the default cardinality is unlimited and I want to limit it to 1.

I am sure I need this somewhere:

->setCardinality(FieldStorageDefinitionInterface::1)

but I can't find where that would be set.

Also, if you know the answer, can you link to the documentation that covers this?

3

Yes, you can limit a custom field to single value by defining a cardinality in the annotations of the field type.

I don't know if you can find this in the docs, but you can use the core comment field as example:

/**
 * Plugin implementation of the 'comment' field type.
 *
 * @FieldType(
 *   id = "comment",
 *   label = @Translation("Comments"),
 *   description = @Translation("This field manages configuration and presentation of comments on an entity."),
 *   list_class = "\Drupal\comment\CommentFieldItemList",
 *   default_widget = "comment_default",
 *   default_formatter = "comment_default",
 *   cardinality = 1,
 * )
 */
class CommentItem extends FieldItemBase implements CommentItemInterface {

When you add a comment field to a content type the cardinality form element is hidden and instead this message is displayed:

Allowed number of values

This field cardinality is set to 1 and cannot be configured.

  • Thank you. This does it. Sadly, "I don't know if you can find this in the docs" seems to be a common answer in Drupal 8. – liquidcms Apr 11 at 14:14
  • 1
    Looks like it's not in the docs. It's in the code comments (it'll be in the annotation class), but you have to know to look there first which is pretty much guess work until you've found it once – Clive Apr 11 at 20:21

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.