所以我有一个搜索栏表单,需要临时连接到一个遗留的非符号页面。当前的get url看起来像下面的(url解码的)
http://localhost:9090/lagacy_page?query=test&platforms[]=Mac,Windows
但是我需要让url看起来像下面的
http://localhost:9090/lagacy_page?query=test&platforms=Mac,Windows
Symfony正在使平台成为一个数组,如果有办法强制它成为逗号分隔的列表,有人反对吗?
这是buildForm方法
/**
* method to build search bar form
*
* @param SymfonyComponentFormFormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
// the platform selector
$builder->add('platform', 'choice',
['choices' => [
Platforms::ALL => 'All Software', // TODO: need to translate this
Platforms::WINDOWS => 'Windows',
Platforms::MAC => 'Mac',
Platforms::IOS => 'iOS',
Platforms::ANDROID => 'Android',
],
'multiple' => true,
'expanded' => true]);
// the actual search bar
$builder->add('query', 'search');
}
您需要覆盖Symfony2如何呈现选择字段。
该文档提供了大量关于如何自定义表单呈现的信息。
如果只有选择类型的搜索表单需要这样做,您将需要创建一个自定义类型,以避免与网站的其他表单发生冲突。
简而言之,如果您使用第一个文档覆盖choice
类型,而不使用自定义类型,则每个choice
类型都将使用相同的行为(您将为搜索表单创建的行为),您可能不希望这样。
一个简单的替代解决方案是将自定义form_div_layout.html.twig
文件直接应用于表单对象。与其他表单不会有任何冲突,因为您只会为搜索表单使用自定义模板。
看完文档后,我的答案会更有意义,你将能够解决你的问题。
您必须使用两个表单元素,因为Symfony以正确的方式(根据HTML规范)
/**
* method to build search bar form
*
* @param SymfonyComponentFormFormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
// the platform selector
$builder->add('platform_choice', 'choice',
['choices' => [
Platforms::ALL => 'All Software', // TODO: need to translate this
Platforms::WINDOWS => 'Windows',
Platforms::MAC => 'Mac',
Platforms::IOS => 'iOS',
Platforms::ANDROID => 'Android',
],
'multiple' => true,
'expanded' => true,
'attr' => [
'class' => 'platform-sorce'
])
->add('platform', 'hidden', [
'attr' => [
'class' => 'real-platform'
]
]);
// the actual search bar
$builder->add('query', 'search');
}
然后添加JS更新您的隐藏字段,因为"platform_choice"已禁用并且不会发送。
$(function(){
var $real_platform = $('.real-platform'),
$platform_source = $('.platform-source');
$platform_source.change(function(){
$real_platform.val($(this).val().join(',');
});
$('#your-form").submit(function(){
$platform_source.attr('disabled', true);
return true;
});
});