我有一个带有动态选择字段“languages”的表单。对于不同的类别,语言可能不同。我希望它们默认都被检查,所以我使用'data'选项。但它只有在我不使用事件时才有效。如果我尝试在我的$ formModifier函数中使用它来动态添加语言它将无法正常工作,并且所有语言都未经检查...任何想法如何修复它?
这是我在ProjectType类
中的buildForm函数public function buildForm(FormBuilderInterface $builder, array $options)
{
(...)
$builder
->add('category', 'choice', array(
'choices' => Category::$NAMES,
'multiple' => false,
'placeholder' => '',
))
->add('name', 'text')
->add('description', 'textarea', array(
'attr' => array('rows' => '10', 'class' => 'tinymce'),
))
->add('save', 'submit', array('label' => 'form.save'));
$formModifier = function (FormInterface $form, User $user, $category = null) {
$languages = null === $category ? array() : $this->userReputation->getAllowedLanguages($user, $category);
$form->add('languages', 'choice', array(
'multiple' => true,
'expanded' => true,
'choices' => $languages,
'data' => array_keys($languages),
));
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier, $user) {
$project = $event->getData();
$formModifier($event->getForm(), $user, $project->getCategory());
}
);
$builder->get('category')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier, $user) {
$category = $event->getForm()->getData();
$formModifier($event->getForm()->getParent(), $user, $category);
}
);
}
我有这个脚本用于在用户更改类别时进行ajax调用:
<script>
function requireReadyFunction() {
var $category = $('#project_category');
// When category gets selected ...
$category.change(function() {
// ... retrieve the corresponding form.
var $form = $(this).closest('form');
// Simulate form data, but only include the selected category value.
var data = {};
data[$category.attr('name')] = $category.val();
// Submit data via AJAX to the form's action path.
$.ajax({
url : $form.attr('action'),
type: $form.attr('method'),
data : data,
success: function(html) {
// Replace current languages field ...
$('#project_languages').replaceWith(
$(html).find('#project_languages')
);
}
});
});
}
</script>