As described in the other answer, you'll want to use a Data Transformer for your entity, and return a new entity if you don't find the one the user has asked for.
There are any number of ways you could to this. This is one way to do it, simplified from an application that just happens to use selectize.js
, but the concepts apply to anyUI you may have on your front-end.
class SubjectTransformer implements DataTransformerInterface
{
protected $em;
public function __construct($em)
{
$this->em = $em;
}
//public function transform($val) { ... }
public function reverseTransform($str)
{
$repo = $this->em->getRepository('AppBundle:Subject');
$subject = $repo->findOneByName($str);
if($subject)
return $subject;
//Didn't find it, so it must be new
$subject = new Subject;
$subject->setName($str);
$this->em->persist($subject);
return $subject;
}
}
Specifically, this DataTransformer
for the entry_type
of a CollectionType
field:
- takes an entity manager in its constructor
- in
reverseTransform
, uses the EM to retrieve a value from the database
- If it doesn't find one, it creates a new entity, and persists it
- explicitly does not flush the entity, in case your form processor/controller wants to perform additional validation on the new entity before actually committing it
Other possible variations include not calling em->persist
; calling em->flush
; or (probably ideally) passing a service to manage search/creation, rather than using the entity manager directly. (Such a service might implement near-duplicate detection, bad-language filtering, only give certain users the ability to create new tags, etc.)