It doesn't work on image field

Created on 29 January 2021, almost 4 years ago
Updated 20 September 2024, 2 months ago

Steps to reproduce

1. Install a fresh Drupal 8 site.
2. Edit the image field in the Article.
3. Go to Field settings and set "Allowed number of values" to Unlimited:

4. Set up the field in Allowed number of values (Cardinality Instance) to Limited:1

5. Create an Article, you will able to add Unlimited images.

πŸ› Bug report
Status

Active

Version

2.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΎUruguay rpayanm

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • πŸ‡³πŸ‡¬Nigeria chike Nigeria

    I just encountered this issue with an image field using Drupal 9.5.11. field_config_cardinality settings on the image field are ignored by the site.

  • πŸ‡ΊπŸ‡¦Ukraine zviryatko

    Added next widget that replaces original one.

    <?php
    /**
     * Add field_config_cardinality support to image widget.
     */
    class CardinalityImageWidget extends ImageWidget {
    
      /**
       * Gets the cardinality of the field.
       *
       * @return int
       *   The cardinality of the field.
       */
      public function getCardinality(): int {
        if (
          $this->fieldDefinition instanceof ThirdPartySettingsInterface
        ) {
          return (int) $this->fieldDefinition->getThirdPartySetting('field_config_cardinality', 'cardinality_config');
        }
    
        return $this->fieldDefinition->getFieldStorageDefinition()
          ->getCardinality();
      }
    
      /**
       * {@inheritdoc}
       */
      protected function formMultipleElements(FieldItemListInterface $items, array &$form, FormStateInterface $form_state) {
        $elements = parent::formMultipleElements($items, $form, $form_state);
        $cardinality = $this->getCardinality();
        $elements["#file_upload_description"]["#cardinality"] = $cardinality;
        if (count(Element::children($elements)) > $cardinality) {
          $elements[$elements["#file_upload_delta"]]['#access'] = FALSE;
        }
        $elements[$elements["#file_upload_delta"]]["#cardinality"] = $cardinality;
        if ($cardinality === 1) {
          $elements[$elements["#file_upload_delta"]]["#multiple"] = FALSE;
        }
        return $elements;
      }
    
    }
    ?>

    and alter original:

    <?php
    
    /**
     * Implements hook_field_widget_info_alter().
     */
    function custom_module_field_widget_info_alter(array &$info) {
      if (isset($info['image_image'])) {
        $info['image_image']['class'] = CardinalityImageWidget::class;
      }
    }
    
    ?>

    The tricky thing is that ImageWidget and FileWidget has complex form that depends on cardinality, so there are now easy way to change it.

Production build 0.71.5 2024