Search code examples
phpjquerysymfonysymfony-3.4

Select2entity not working with embed forms


I have this code

->add('product', Select2EntityType::class, [
            'remote_route'          => 'search',
            'class'                 => Product::class,
            'primary_key'           => 'id',
            'text_property'         => 'name',
            'minimum_input_length'  => 2,
            'page_limit'            => 10,
            'allow_clear'           => true,
            'delay'                 => 250,
            'cache'                 => true,
            'cache_timeout'         => 60000, // if 'cache' is true
            'language'              => 'fr',
            'placeholder'           => 'yep',
            'allow_add'             => [
                'enabled'               => true,
                'new_tag_text'          => '',
                'tag_separators'        => '[".", ","]'
            ],
            'multiple'             => false,
            'attr'                 => [
                'style' => 'width:100%'
            ],
            'scroll'               => true,
        ])

My html :

{% block main %}
<div class="box-body">
    <div class="row">
       <div id="dynamic-relations-elements" class="hidden">
    </div>
</div>
{% endblock %}

{% block body_javascript %}
    {{ parent() }}
    <script src="{{ asset('build/js/users.js') }}"></script>
    <script src="{{ asset('bundles/tetranzselect2entity/js/select2entity.js') }}"></script>
{% endblock body_javascript %}

In ventilation.js I have :

$('#dynamic-relations-elements').removeClass('hidden');
  $.ajax({
     type: "GET",
     url: Routing.generate('create'),
     success: function (response) {
        $('#dynamic-relations-elements').html(response);
     }
})

And the route for building form :

/**
 * @Route("/ajax/product-create", name="create",
 *     options      = { "expose" = true })
 * @param Request $request
 * @return Response
 */
public function createProduct()
{
    $productVen = new Product();

    $form = $this->createForm(ProductType::class, $productVen);

    return $this->render('/users/add-product.html.twig', [
        'form' => $form->createView(),
    ]);
}

The problem is that the selectbox is not initalized. I have for field product a simple text input and not an selectbox. I have no errors in browser console. Any ideas please ? Thx in advance


Solution

  • If you look at the source lines 144 - 148 you will see how the elements are initialized:

    (function ($) {
        $(document).ready(function () {
            $('.select2entity[data-autostart="true"]').select2entity();
        });
    })(jQuery);
    

    In your case this initially happens before the form exists. So it looks like you just need to manually initialize the element.
    Try something like this:

    $.ajax({
         type: "GET",
         url: Routing.generate('_route_ventilation_products_create'),
         success: function (response) {
             let $dre = $('#dynamic-relations-elements');
             $dre.html(response);
             let $s2 = $dre.find('.select2entity');
             $s2.select2entity();
             $s2.on('change', function(){
               // do something with selected value
               console.log(this.id, $(this).find(':selected').val());
             });
         }
    })