DrupalX

Extension
Framework

Cardinality detection

Drupal allows to set a "cardinality" for all fields you define. You can choose whether a certain field can contain just one single value or whether you can add as many values as you like. For the special case when we're dealing with single-value fields, the cardinality is simply 1. This basically means, that everything is an array - even a simple string or integer value.

By default, Drupal, doesn't do much to hide this internal fact from you. That means, you will very often (either in a Twig template or in PHP) need to be aware of this when accessing "simple" single-value fields:

{{ content.field_myfield.0 }}

In this small example, we're accessing a simple string field called "myfield". The ".0" at the end is required, however, because the field might be configured to contain multiple values. This, of course, isn't really a pleasant experience from a developer's point-of-view.

To make it even more confusing, you can, with standard Drupal, sometimes omit the ".0". This is the case, when you are accessing a property of that field. Drupal will then automatically return the corresponding value of the first element:

{{ content.field_myimage.width }}

Watch out, though: Drupal will always do this, even when your field has a cardinality > 1. That means: If you are using that field to save multiple images instead of just one, the expression above will still return a width - but only for the first image which is most probably not what you want. This can lead to difficult to find errors. 

Even more confusing is the fact that this "shortcut" only applies to properties. You won't be able, for example, to call methods like "getValue" etc. The following example won't work:

{{ content.field_myimage.getValue() }}

This example has to be rewritten as:

{{ content.field_myimage.0.getValue() }}

DrupalX fixes all this by automatically detecting how a field is configured: Everything stays the same, if you have actually configured the field to allow multiple values. If, however, the field is restricted to a single value (usually the most common case), DrupalX will extract the first element for you:

{{ $myfield }}

You'll notice that there isn't a ".0" at the end. More information on the other aspects of this syntax can be found under the chapter on field access operators.