Impossible to populate a multivalued field (cardinality >1) !?

Created on 21 September 2023, about 1 year ago

Problem/Motivation

I am surprised that I cannot simply feed the checkbox informations from the webform into an entity.

Steps to reproduce

1) Create an entity (like a content/node) with a taxonomy term multivalued entity reference field.
2) Create a webform with a checkbox element powered by the same vocabulary and allow multiple values.
3) In the webform_entity_handler in Identity Creation mode, simply map the 2 pieces of information using one of the suggestions from the drop-down list.
4) By submitting the webform, we obtain a message:
InvalidArgumentException: Value is not a valid entity. in Drupal\Core\Entity\Plugin\DataType\EntityReference->setValue() (line 106 of www/core/lib/Drupal/Core/Entity/Plugin/DataType/EntityReference.php).

Proposed resolution

in src/Plugin/WebformHandler/WebformEntityHandler.php:

Before:

       if (empty($entity)) {
          // Create the entity with the values.
          $entity = $this->entityTypeManager->getStorage($type)->create($data);
      }

Proposed solution:

       if (empty($entity)) {
          // Create the entity with the values.
          $entity = $this->entityTypeManager->getStorage($type)->create( array(
                'type'  => $data['type'],
                'title' => $data['title'],
          ));
          unset($data['type']);
          unset($data['title']);

          [$type, $bundle] = explode(':', $this->configuration['entity_type_id']);
          $fieldDefinitions = \Drupal::service('entity_field.manager')->getFieldDefinitions($type, $bundle);
          foreach ($data as $field => $value) {
             $cardinality = $fieldDefinitions[$field]->getFieldStorageDefinition()->getCardinality();
             if (!is_array($value) || ($cardinality == 1)) {
                  $entity->set($field, $value);
             }  else {
                foreach ($value as $item) {
                   if ($entity->get($field)->isEmpty()) {
                      $entity->set($field, $item);
                   } else {
                      $entity->get($field)->appendItem($item);
                   }
                }
             }
          }
       }

Remaining tasks

I think we also need to study the case of an entity update (I don't have this need immediately, I haven't looked for a solution).

User interface changes

None.

API changes

None.

Data model changes

None.

🐛 Bug report
Status

Active

Version

2.0

Component

Code

Created by

🇫🇷France marco5775

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

Comments & Activities

Production build 0.71.5 2024