Use the initial element for database if the value was not changed.

This commit is contained in:
Jan Böhmer 2023-07-15 21:00:45 +02:00
parent 8ea92ef330
commit 422fa01c6f

View file

@ -59,20 +59,24 @@ class StructuralEntityChoiceLoader extends AbstractChoiceLoader
public function createNewEntitiesFromValue(string $value): array 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) === '') { if (trim($value) === '') {
throw new \InvalidArgumentException('Cannot create new entity, because the name is empty!'); 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']; $class = $this->options['class'];
/** @var StructuralDBElementRepository $repo */ /** @var StructuralDBElementRepository $repo */
$repo = $this->entityManager->getRepository($class); $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 * @return AbstractStructuralDBElement|null
*/ */
public function getStartingElement(): ?AbstractStructuralDBElement 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 * @param AbstractStructuralDBElement|null $starting_element
* @return StructuralEntityChoiceLoader * @return StructuralEntityChoiceLoader
*/ */