我盡量保持簡短。
我想根據另一個 ChoiceType(N.1) 更改我的 ChoiceType(N.2) 的可能選擇選項。
- 我的 ChoiceType(N.1) 未映射并具有“是”或“否”選項
- My ChoiceType(N.2) 被映射并填充了資料庫中的類別。
資料庫具有 Columns ID(int) | 名稱(字串) | 收入(布林值)
因此,如果用戶選擇 Option Yes,我希望 ChoiceType (N.2) 中的所有類別的收入為 1(true)。如果用戶選擇否,我想顯示收入為 0(布林值)的類別的所有選擇選項
我已經做了很多研究,但我就是無法讓它發揮作用。我主要關注 de documentaion https://symfony.com/doc/current/form/dynamic_form_modification.html,但是這兩個 ChoiceTyps 都是物體,而不僅僅是一個。我應該幾乎擁有它,但我不知道缺少什么。以下是我的代碼的重要部分:
報名表:
->add('choice', ChoiceType::class, [
'choices' => [
'No' => 0,
'Yes' => 1,
],
'data'=>0,
'mapped' => false,
])
$formModifier = function (FormInterface $form, $choice) {
$revenue = $choice;
$user = $this->security->getUser();
$userId = $user->getId();
$form->add('category', EntityType::class,[
'class'=>Category::class,
'query_builder' => function(CategoryRepository $repository) use($userId,
$revenue) {
$qb = $repository->createQueryBuilder('u');
return $qb
->where('u.user=' .$userId, 'u.revenue='. $revenue );
}, ]);
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
$data = $event->getData();
$form = $event->getForm();
$choice = $form->get('choice')->getData();
$formModifier($event->getForm(), $choice);
}
);
$builder->get('choice')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
$choice = $event->getForm()->getData();
$formModifier($event->getForm()->getParent(), $choice);
}
);
AJAX
var $choice = $('#entry_choice');
$choice.change(function() {
var $form = $(this).closest('form');
var data = {};
var choice = $('#entry_choice').val();
data= choice;
data[$choice] = 1;
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data : data,
complete: function(html) {
console.log( data);
$('#entry_category').replaceWith(
$(html.responseText).find('#entry_category'));
}
});
});
我想我沒有正確理解從 ajax 傳遞的資料。我正在嘗試實作以下目標:如果用戶將 ChoiceType 從 No 更改為 Yes,則將值為 1 的變數 $choice 傳遞給表單。在 $formModifier 的表單中,它應該將變數 $revenue 更改為 $choice,以便我可以使用我的 query_builder 過濾所有收入為 1 的類別。('u.revenue='.$revenue)
親切的問候馬格努斯
uj5u.com熱心網友回復:
而不是data[$choice] = 1;嘗試data[$choice.attr('name')] = 1;
Symfony 期望資料以特定格式從前端發送。
如果您檢查生成的 html 表單的來源,您將看到該格式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/424083.html
上一篇:為什么我從Ajax呼叫將JSON物件作為ASP.NETCore中的資料傳遞給控制器??中的空物件?
下一篇:在一頁Jquery中發送多個資料
