Select2entity 不适用于嵌入表单

Select2entity not working with embed forms

我有这个代码

->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,
        ])

我的 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 %}

ventilation.js 我有 :

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

以及建筑形式的路线:

/**
 * @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(),
    ]);
}

问题是选择框没有初始化。我有字段 product 一个简单的文本输入而不是一个选择框。我在浏览器控制台中没有错误。有什么想法吗?提前致谢

如果您查看 source 第 144 - 148 行,您将看到元素是如何初始化的:

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

在您的情况下,这最初发生在表单存在之前。所以看起来你只需要手动初始化元素。
尝试这样的事情:

$.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());
         });
     }
})