我已准备好表单事件
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
我可以看到以下信息。
我想做的就是更改
value
的 key
,您会看到红色箭头指向的位置,以便继续该过程的其余部分,需要新的 value
而不是旧的。
我使用的方法似乎可以改变值,但是一旦我移出 foreach 循环,旧值仍然存在,我需要做什么才能使
qqq
被例如 444
替换为其余部分过程?
在您的
onPreSubmit
函数中,您需要使用您修改的数组设置事件数据:
public function onPreSubmit(FormEvent $event){
$interestTags = $event->getData();
$interestTags = $interestTags['interest'];
foreach($interestTags as $key => $interestTag){
$interestTags[$key] = "55";
}
}
$event->setData($interestTags);
}
使用 PRE_SUBMIT
$builder
->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event): void {
$entity = $event->getForm()->getData();
$entity->setEntityField('New value');
$event->getForm()->setData($entity);
}
);