gpt4 book ai didi

symfony-2.1 - 表格 : Avoid setting null to non submitted field

转载 作者:行者123 更新时间:2023-12-04 02:55:15 24 4
gpt4 key购买 nike

我有一个简单的模型(源代码的简化):

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',
));
}
}

我的 Controller :
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 , react 是我所期望的:
Collection Object
(
[page:public] => 2
[limit:public] => 20
)

现在,当我 POST /users/?form[page]=3 ,响应为:
Collection Object
(
[page:public] => 3
[limit:public] =>
)
limit变为 null,因为它没有被提交。

我想得到
Collection Object
(
[page:public] => 3
[limit:public] => 10 // The default value, set before the bind
)

问题 :如何更改表单行为,使其忽略未提交的值?

最佳答案

如果只是参数(GET参数)的问题,您可以将默认值定义到路由文件中

route_name:
pattern: /users/?form[page]={page}&form[limit]={limit}
defaults: { _controller: CompanyNameBundleName:ControllerName:ActionName,
limit:10 }

另一种方法是使用 Hook (即 PRE_BIND )并将该值手动更新到此事件中。这样,您就没有将“逻辑”传播到多段代码中。

最终代码 - 由 Adrien 建议 - 将是
<?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);
}
}
}
}

关于symfony-2.1 - 表格 : Avoid setting null to non submitted field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11687760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com