The creation of new entities is done in a method used as an #element_validate callback.
The widget API in D8 has the massageFormValues() method, which would be much more adapted to the task (also, results in less stuff being serialized in the $form)

Comments

yched’s picture

Priority: Normal » Major

Side note: this actually become a requirement once we start actually running validate() and make use of our constraints:
EntityReferenceItem::getPropertyDefinitions() specifies that 'target_id' has to be a positive int.
But the autocomplete widget generates items with 'target_id' = 'the label of the auto_create entity', thus fails validation.

yched’s picture

Priority: Major » Normal

Bumping down. The issue mentioned in #1 is actually also encountered by the taxo autocomplete widget, and is triggered by something else. I opened #2012662: Constraints on 'target_id' / 'tid' properties break autocomplete if applied for this.

Still, the refactoring mentioned in the OP would make very much sense :-)

amateescu’s picture

Issue summary: View changes
Status: Active » Postponed (maintainer needs more info)

I looked a bit into doing this at the post-DrupalcampGhent sprint but there are a few problems:

  1. ER actually does some validation in the elementValidate() method:
          ...
          if ($value === NULL) {
            // Try to get a match from the input string when the user didn't use the
            // autocomplete but filled in a value manually.
            $handler = \Drupal::service('plugin.manager.entity_reference.selection')->getSelectionHandler($this->fieldDefinition);
            $value = $handler->validateAutocompleteInput($element['#value'], $element, $form_state, $form, !$auto_create);
          }
          ...
    

    I'm not sure the semantics of massageFormValues() is ok with that?

  2. there's a slight performance issue too: elementValidate() is only called once during a successful form submission, while massageFormValues() is called three times
amateescu’s picture

Status: Postponed (maintainer needs more info) » Closed (duplicate)
yched’s picture

Yay :-)