我有以下問題。我的 Symony 6 專案中有兩個表:
- 文章
- 變體
這兩個表相互關聯,因為一篇文章可以有多個變體,并且一個變體始終屬于一篇文章。
現在我有一個表單來創建一個新的變體,我必須在其中選擇相應的文章。為此,我想使用 EntityType 欄位作為下拉選單。
問題是我在文章表中有多達 100,000 篇文章,這在一次加載所有選項時會導致巨大的加載問題。因此,我考慮使用 Select2 以便僅在輸入 1-2 個字符后進行查詢,并且僅在下拉串列中顯示與搜索匹配的文章。
JS:
$(#sizes).select2({
ajax: {
url: {{ path("text_ajax_load_select_option") }},
dataType: 'json',
type: 'GET',
data: function (params) {
var queryParameters = {
term: params.term,
}
return queryParameters;
},
processResults: function (data) {
return {
results: $.map(data.selectOptions, function (selectOptions) {
return {
text: selectOptions.title,
id: selectOptions.title
}
})
};
}
}
})
帶有 EntityType Dropdown 的新表單 (VariantenType) 可根據 select2 欄位中的搜索輸入動態填充:
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
// .. other
->add('base_article', EntityType::class, [
'class' => Artikel::class,
'multiple' => false,
'choice_label' => 'title',
'label' => 'Base Article',
'choices' => [],
])
;
}
我會很高興有任何想法和建議。
uj5u.com熱心網友回復:
您只需PRE_SUBMIT向您的 FormBuilder 添加一個事件偵聽器:
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
// ... other properties
->add('base_article', EntityType::class, [
'class' => Artikel::class,
'choice_label' => 'title',
'label' => 'Base Article',
'choices' => [],
'attr' => [
'class' => 'select2article'
]
]);
$builder->addEventListener(
FormEvents::PRE_SUBMIT,
function (FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
if(isset($data['base_article']) and $data['base_article']!=null){
$selected = $data['base_article'];
$form->add('base_article', EntityType::class, array(
'class' => Artikel::class,
'choice_label' => 'title',
'label' => 'Base Article',
'attr' => [
'class' => 'select2article'
],
'query_builder' => function (EntityRepository $er) use ($selected){
return $er->createQueryBuilder('a')
->where('a.id = :id')
->setParameter('id', $selected);
},
));
}
}
);
}
JS
$('.select2article').select2({
ajax: {
url: {{ path("text_ajax_load_select_option") }},
dataType: 'json',
type: 'GET',
data: function (params) {
var queryParameters = {
term: params.term,
}
return queryParameters;
},
processResults: function (data) {
return {
results: $.map(data.selectOptions, function (selectOptions) {
return {
text: selectOptions.title,
id: selectOptions.id
}
})
};
}
}
})
So after sending the request, we get into our event listener. There we will get the selected id of the base_article property, after which we will add the query_builder parameter to the form with the selection by id from the Artikel entity
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/456397.html
標籤:php 交响乐 jQuery-select2 symfony 形式 symfony6
下一篇:教義IF宣告
