dpsyssiv90846 2016-02-09 14:52
浏览 52
已采纳

Symfony2删除FormType中的空字段

I have a onPreSubmit in my Symfony2 FormType.

public function onPreSubmit(FormEvent $event)
{
    $data = $event->getData();

    // Avoid sending empty RegisterProduct
    foreach ($data['registerProducts'] as $key => $registerProduct) {

        if (empty($registerProduct['quantity'])) {
            unset($data['registerProducts'][ $key ]);
        }
    }

    $event->setData($data);
}

The purpose is to remove an array value if a certain fiels in this one is empty (which works)

But when I set the data I have this error:

An exception occurred while executing 'INSERT INTO register_product ..... 
Integrity constraint violation: 1048 Column 'register_id' cannot be null

I don't understand why.

EDIT: I tried with onPostSubmit, but still have the same error

public function onPostSubmit(FormEvent $event)
{
    /** @var Register $register */
    $register = $event->getForm()->getData();

    foreach ($register->getRegisterProducts() as $registerProduct) {

        if ($registerProduct->getQuantity() < 1) {
            $register->removeRegisterProduct($registerProduct);
        }
    }
}
  • 写回答

1条回答 默认 最新

  • doulianxi0587 2016-02-09 15:23
    关注

    As say in comments, you should do it in postSubmit instead of preSubmit.

    Example :

    public function onPostSubmit(FormEvent $event) {
        $data = $event->getData();
    
        foreach ($data['registerProducts'] as $key => $registerProduct) {
    
            if (empty($registerProduct['quantity'])) {
                unset($data['registerProducts'][$key]);
            }
        }
    });
    

    If the SQL error persists, try to replace $event->getData() by $event->getForm()->getData() , the first returns data from the client.

    EDIT

    Unfortunately, the FormEvent doesn't work.

    Also, I'll propose to use the prePersist and preUpdate hooks in your Entity.
    It may not be an alternative for you if your question is only about the form context.

    Usage :

    /**
     * @ORM\HasLifecycleCallbacks
     * @ORM\Entity
     */
    class YourEntity
    {
        // ...
    
        /**
         *
         * @ORM\PrePersist
         * @ORM\PreUpdate
         */
        public function manageProducts()
        {
            foreach ($this->getRegisterProducts() as $registerProduct) {
                if ($registerProduct->getQuantity() < 1) {
                    $this->removeRegisterProduct($registerProduct);
                }
            }
        }
    }
    

    See the Events part of doctrine documentation.

    I hope you can use this solution and that it works.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄