diff --git a/src/Form/Type/Helper/StructuralEntityChoiceLoader.php b/src/Form/Type/Helper/StructuralEntityChoiceLoader.php index 5d466a73..df98e6ea 100644 --- a/src/Form/Type/Helper/StructuralEntityChoiceLoader.php +++ b/src/Form/Type/Helper/StructuralEntityChoiceLoader.php @@ -59,20 +59,24 @@ class StructuralEntityChoiceLoader extends AbstractChoiceLoader public function createNewEntitiesFromValue(string $value): array { - if (!$this->options['allow_add']) { - //Always allow the starting element to be added - if ($this->starting_element !== null && $this->starting_element->getID() === null) { - $this->entityManager->persist($this->starting_element); - return [$this->starting_element]; - } - - throw new \RuntimeException('Cannot create new entity, because allow_add is not enabled!'); - } - if (trim($value) === '') { throw new \InvalidArgumentException('Cannot create new entity, because the name is empty!'); } + //Check if the value is matching the starting value element, we use the choice_value option to get the name of the starting element + if ($this->starting_element !== null + && $this->starting_element->getID() === null //Element must not be persisted yet + && $this->options['choice_value']($this->starting_element) === $value) { + + //Then reuse the starting element + $this->entityManager->persist($this->starting_element); + return [$this->starting_element]; + } + + if (!$this->options['allow_add']) { + throw new \RuntimeException('Cannot create new entity, because allow_add is not enabled!'); + } + $class = $this->options['class']; /** @var StructuralDBElementRepository $repo */ $repo = $this->entityManager->getRepository($class); @@ -103,6 +107,7 @@ class StructuralEntityChoiceLoader extends AbstractChoiceLoader } /** + * Gets the initial value used to populate the field. * @return AbstractStructuralDBElement|null */ public function getStartingElement(): ?AbstractStructuralDBElement @@ -111,6 +116,7 @@ class StructuralEntityChoiceLoader extends AbstractChoiceLoader } /** + * Sets the initial value used to populate the field. This will always be an allowed value. * @param AbstractStructuralDBElement|null $starting_element * @return StructuralEntityChoiceLoader */