forms - 如何对 Symfony2 表单集合项进行排序

标签 forms symfony doctrine-orm symfony-forms formcollection

我有一个实体 Recipe带有分配给的步骤的表单集合。

用户可以通过拖放和一些 javascript 对步骤进行排序。
为了保存新订单,我添加了一个字段 step_number到每个步骤,然后由 javascript 自动填充。

为了确保步骤以正确的顺序显示,我使用 @ORM\OrderBy({"step_number" = "ASC"})在我的食谱实体中。

唯一的问题是:如果用户提交表单并且有一些错误,表单会再次显示,但不是以正确的步骤顺序显示,因为它们不是从数据库中获取的。

我试图通过使用这样的 eventListener 手动排序集合来解决这个问题:

$builder->get('steps')->addEventListener(FormEvents::SUBMIT, function(FormEvent $event){
                $steps = $event->getData();

                $steps[1]->setStepnumber('8');//does not affect the rendered form
                $event->setData($steps);

                \Doctrine\Common\Util\Debug::dump($event->getData());
                //add some logic to sort the steps

});

这是转储的样子:
array(2) {
  [0]=>
  object(stdClass)#1212 (8) {
    ["__CLASS__"]=>
    string(29) "CoBo\RecipeBundle\Entity\Step"
    ["id"]=>
    int(244)
    ["recipe"]=>
    string(31) "CoBo\RecipeBundle\Entity\Recipe"
    ["step_number"]=>
    string(1) "2"
    ["description"]=>
    string(3) "test description 1"
  }
  [1]=>
  object(stdClass)#1220 (8) {
    ["__CLASS__"]=>
    string(29) "CoBo\RecipeBundle\Entity\Step"
    ["id"]=>
    int(245)
    ["recipe"]=>
    string(31) "CoBo\RecipeBundle\Entity\Recipe"
    ["step_number"]=>
    string(1) "8"
    ["description"]=>
    string(4) "test description 2"

  }
}

但是$steps[1]->setStepnumber('8');的修改不影响呈现的形式。 step[1]还是有旧号码。
我不知道我在这里做错了什么。
对步骤进行排序的不同方法也会有所帮助。

最佳答案

您应该使用 FormEvents::PRE_SET_DATA反而。因为在 FormEvents::POST_SUBMIT 之后您设置的数据不会再次设置为表单数据。因此,您看不到更改的数据。

请看https://github.com/symfony/Form/blob/master/Form.php查看在哪些操作之后调度了哪个表单事件。

还可以查看官方表单事件文档。

http://symfony.com/doc/current/components/form/form_events.html

关于forms - 如何对 Symfony2 表单集合项进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17126081/

相关文章:

php - 为商店订单生成唯一的序列号

symfony2 : trying to load fixtures using hautelook/alicebundle

jquery - 使用外部提交按钮提交 Rails Remote_form

php - Zend 在 Zend 表单中验证邮政编码 -> 根据给定国家/地区进行验证

javascript - 使用取消按钮单击提交按钮后防止提交表单

php - Symfony 如何验证 EntityType 字段

symfony - form_errors() 不显示错误

javascript - 如何使用javascript或jquery将html表单数据保存到sql db

html - 如何在 Victoire 生成的小部件中添加 HTML 属性

php - 教义2 : OneToMany relation