表单:避免为未提交的字段设置 null [英] Form: Avoid setting null to non submitted field
问题描述
我有一个简单的模型(源代码的简化):
I've got a simple model (simplified of source):
class Collection
{
public $page;
public $limit;
}
还有一个表单类型:
class CollectionType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('page', 'integer');
$builder->add('limit', 'integer');
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'FSC\Common\Rest\Form\Model\Collection',
));
}
}
我的控制器:
public function getUsersAction(Request $request)
{
$collection = new Collection();
$collection->page = 1;
$collection->limit = 10;
$form = $this->createForm(new CollectionType(), $collection)
$form->bind($request);
print_r($collection);exit;
}
当我 POST/users/?form[page]=2&form[limit]=20
时,响应是我所期望的:
When i POST /users/?form[page]=2&form[limit]=20
, the response is what i expect:
Collection Object
(
[page:public] => 2
[limit:public] => 20
)
现在,当我POST/users/?form[page]=3
时,响应是:
Now, when i POST /users/?form[page]=3
, the response is:
Collection Object
(
[page:public] => 3
[limit:public] =>
)
limit
变为 null,因为它没有提交.
limit
becomes null, because it was not submitted.
我想得到
Collection Object
(
[page:public] => 3
[limit:public] => 10 // The default value, set before the bind
)
问题:如何更改表单行为,使其忽略未提交的值?
Question: How can i change the form behaviour, so that it ignores non submitted values ?
推荐答案
如果只是参数(GET参数)的问题可以在路由文件中定义默认值
If is only a problem of parameters (GET parameters) you can define the default value into routing file
route_name:
pattern: /users/?form[page]={page}&form[limit]={limit}
defaults: { _controller: CompanyNameBundleName:ControllerName:ActionName,
limit:10 }
另一种方法是使用钩子(即PRE_BINDa>) 并手动将该值更新到此事件中.这样,您就不会将逻辑"分散到多段代码中.
An alternative way could be to use a hook (i.e. PRE_BIND) and update manually that value into this event. In that way you haven't the "logic" spreaded into multi pieces of code.
最终代码 - 由 Adrien 建议 - 将是
Final code - suggested by Adrien - will be
<?php
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvents;
class IgnoreNonSubmittedFieldSubscriber implements EventSubscriberInterface
{
private $factory;
public function __construct(FormFactoryInterface $factory)
{
$this->factory = $factory;
}
public static function getSubscribedEvents()
{
return array(FormEvents::PRE_BIND => 'preBind');
}
public function preBind(FormEvent $event)
{
$submittedData = $event->getData();
$form = $event->getForm();
// We remove every child that has no data to bind, to avoid "overriding" the form default data
foreach ($form->all() as $name => $child) {
if (!isset($submittedData[$name])) {
$form->remove($name);
}
}
}
}
这篇关于表单:避免为未提交的字段设置 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!