Dynamically modify form preset choices to pass validation in symfony2
<p>I want to be able to dynamically add entities without having them preset in the choices option for EntityType form type. I need to modify available choices, because otherwise <code>invalid value</code> error pops up.</p>

<pre><code>class MyImageType extends AbstractType {
    public function __construct($em) {
        $this-&gt;em = $em;
    }

    public function configureOptions(OptionsResolver $resolver) {
        $resolver-&gt;setDefaults(array(
            'class' =&gt; 'stuff/MyImage',
            'choice_label' =&gt; 'id',
            'multiple' =&gt; true,
            'choices' =&gt; [],
        ));
    }

    public function buildForm(FormBuilderInterface $builder, array $options) {
        //
    }

    public function getParent() {
        return EntityType::class;
    }
}
</code></pre>

<p>and I'm using it like this:</p>

<pre><code>$builder-&gt;add('images', 'stuff\MyImage\Form\Type\MyImageType')
</code></pre>

<p>the html generated looks like this:</p>

<pre><code>&lt;select id="product_images" name="product[images][]" required="required" class="form-control" multiple="multiple"&gt;
&lt;/select&gt;
</code></pre>

<p>I'm executing some ajax calls to create entity and append the id to the dropdown like so:</p>

<pre><code>&lt;select id="product_images" name="product[images][]" required="required" class="form-control" multiple="multiple"&gt;
    &lt;option value="88" selected="selected"&gt;88&lt;/option&gt;
&lt;/select&gt;
</code></pre>

<p><code>88</code> is existing ID for existing entity.</p>

<p>If I submit the form after that, <code>invalid value</code> error shows up, because <code>88</code> is not in the preset <code>choices</code> for this entity type. So I need to add <code>88</code> in the available choices.</p>

<p>If this was a child of a form (Symfony\Component\Form\Form), I could do this on <code>FormEvents::PRE_SUBMIT</code></p>

<pre><code>//..
$img = $em-&gt;findOneById(88);
$form-&gt;add('images', [
    'class' =&gt; 'stuff/MyImage',
    'choice_label' =&gt; 'id',
    'multiple' =&gt; true,
    'choices' =&gt; [$img],
]);
</code></pre>

<p>but in my case I want to do it inside <code>MyImageType</code> class to encapsulate the class. Can you give me directions how to do it? Thanks.</p>

<p><strong>EDIT:</strong></p>

<p>In the process of writing this question I've found a solution to this. In the event I can update the field like so:</p>

<pre><code>$builder-&gt;addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use($em) {
    $form = $$event-&gt;getForm();
    $form-&gt;getParent()-&gt;add('images', EntityType::class, $options);
}
</code></pre>

<p>Still I don't want to answer my own question, because maybe there is a better way to do it. Thanks.</p>