Symfony使用表单事件在提交之前更改数据

时间:2016-05-26 07:08:17

标签: php symfony

我已准备好表格活动FormEvents::PRE_SUBMIT

namespace AppBundle\Form\EventListener;

use Doctrine\ORM\EntityManager;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;


class AddProfileFieldSubscriber implements EventSubscriberInterface
{
    protected $authorizationChecker;

    protected $em;

    function __construct(AuthorizationChecker $authorizationChecker, EntityManager $em)
    {
        $this->authorizationChecker = $authorizationChecker;
        $this->em = $em;
    }

    public static function getSubscribedEvents()
    {
        // Tells the dispatcher that you want to listen on the form.pre_set_data
        // event and that the preSetData method should be called.
        return array(
            FormEvents::PRE_SUBMIT => 'onPreSubmit'
        );
    }


    /**
     * @param FormEvent $event
     */
    public function onPreSubmit(FormEvent $event){

        $interestTags = $event->getData();
        $interestTags = $interestTags['interest'];
        foreach($interestTags as $key => $interestTag){
                $interestTags[$key] = "55";
            }
        }
}

在函数onPreSubmit内,如果我转储$event,我可以看到以下信息。

enter image description here

我想要做的就是更改value的{​​{1}},其中您会看到指向红色箭头的位置,以便继续执行剩余的key而不是value而不是旧的。

我使用的方法似乎改变了值,但是一旦我离开foreach循环,旧值仍然存在,我需要做什么才能将qqq替换为例如{{1其余的过程?

1 个答案:

答案 0 :(得分:3)

onPreSubmit函数中,您需要使用修改后的数组设置事件数据:

public function onPreSubmit(FormEvent $event){

        $interestTags = $event->getData();
        $interestTags = $interestTags['interest'];
        foreach($interestTags as $key => $interestTag){
                $interestTags[$key] = "55";
            }
        }
        $event->setData($interestTags);
}