Q:

How to populate an ArrayCollection variable with existing data from a form?

I'm kind of new with Symfony, and I have a question.
I'm currently making a Gallery Bundle (consisting of 'Gallery' and 'Image' entities), and here comes my problem.
I can upload images as well as use my entity Image corresponding to the file, but then I'd like to categorize my images into galleries. I made a One-To-Many relationship between my Gallery and Image entities, with an ArrayCollection $images (into Gallery Entity) that should represents the images.
Now, how can I populate that $images variable from a browser ?
I thought of that solution : add a text field into the Gallery entity, with the images names, and before persisting the Gallery entity, I would fetch the corresponding Images entities and put them into my variable $images, but the problem is that I can't access the entity manager from an entity..
Thanks for the help, if you need code I can of course show you, even if it's pretty basic.
EDIT: I found a way to get access to the entity manager from an entity, but it is said to be unsecure. For the time being I'll probably use that, but if someone can explain to me a better way, I'll take it.

A:

You could write a service injected with the entity manager which can create &/or update a gallery from an array of $image names and have your controller call that rather than having your entity dependent on the entity manager. For example: (see link above for how to configure the service in services.yml)
class GalleryManager
{
    private $entityManager;

    public function __construct(\Doctrine\ORM\EntityManager $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function updateGalleryImages(Gallery $gallery, array $imageNames)
    {
        ...
    }
}

However, I'm not sure if typing in image names is the best approach here. How will you ensure your image names are unique? Handle names that aren't found? Handle duplicate names? Does it matter how usable the interface is? How about efficiency - one query for each image name? how many is a gallery likely to contain?
An alternative user interface would be to provide some sort of image search/list and allow the user to select images from the results to add to the gallery - in this case the selection should come back as an array of Image entities if implemented correctly. At it's simplest, for a small number of images this could just be a multi-selectable list box of all image names although ideally the user would want to see thumbnail previews of the images they're choosing from. 
A basic list box of all image names (or set of checkboxes) could be implemented using a form (data_class Gallery) with an entity field for the images collection. This would map directly onto gallery->images and the entity would never need to depend on EntityManager. 
Selecting from a filtered set of images is more complex although I can point you in the right direction if it's of interest to you.

