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

Bai*_*aig 3 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";
            }
        }
}
Run Code Online (Sandbox Code Playgroud)

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

在此处输入图片说明

所有我想要做的是改变valuekey,你看到红色箭头所指向,使移动的过程的其余部分采取新的value,而不是旧的。

我使用的方法似乎可以更改值,但是一旦我退出 foreach 循环,旧值仍然存在,我需要做什么才能将qqq其替换为例如444过程的其余部分?

Vev*_*eve 6

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

public function onPreSubmit(FormEvent $event){

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