【问题标题】:Symfony change object injected in form using Listener使用监听器以表单形式注入的 Symfony 更改对象
【发布时间】:2018-06-19 10:30:25
【问题描述】:

我正在使用 Symfony 3.4,我有一件奇怪的事情要做,我会尽量解释清楚。

我有一个实体Website 和一个WebsiteFormType,在这个WebsiteFormType 我有一个像这样的监听器:(在formType 中buildForm() 的第一行)

$builder->addEventSubscriber(new WebsiteListener();

在这个监听器中,我需要在提交表单时检查特定值何时更新,如果此值更新,我需要复制我的对象,例如当我更新我的网站并更改 @987654327 @ 从http://xxx.xxhttp://yyyy.yy 我复制了我的第一个网站来创建第二个网站,而不是仅仅更新字段url

在这个 Listener 中,我使用 preSubmitpostSubmit

我的问题是,当我更改网址时,我需要更改链接到表单的对象网站。

如果http://xxx.xx 是WebsiteA 而http://yyyy.yy 是WebsiteB,当我提交WebsiteA 并更改url 时,我需要将链接到表单的Website 对象从WebsiteA 更改为WebsiteB....

这是因为如果我在此之后重新验证表单,则验证的是 WebsiteB 而不是 WebsiteA。

不知道你是否理解我的问题:) 谢谢!

【问题讨论】:

标签: symfony


【解决方案1】:

尝试使用 Doctrine EventSubscriber,例如:

class OrderListener implements EventSubscriber {

protected $statusChanges = false;

public function getSubscribedEvents()
{
    return array(
        'preUpdate',
        'postUpdate',
    );
}

public function preUpdate(PreUpdateEventArgs $args)
{
    $changeSet = $args->getEntityChangeSet();
    foreach ($changeSet as $key => $arr) {

        if ($key === 'status' && (int)$arr[0] !== (int)$arr[1]) {
            $this->statusChanges = true;
        }
    }
}

public function postUpdate(LifecycleEventArgs $args)
{
    $entity = $args->getObject();

    if ($entity instanceof Order && $this->statusChanges) {
        $repo = $args->getObjectManager()->getRepository(Action::class);
        $action = new Action();
        $action->setOrder($entity)
            ->setStatus($entity->getStatus())
            ->setCost($entity->getCost())
            ->setTimeAt(new \DateTime())
            ->setPoint($entity->getPoint())
            ->setDescription($entity->getDescription())
            ->setService($entity->getService())
        ;

        $repo->persistAndFlush($action); // custom method, you can use $args->getObjectManager()->persist($action) and $args->getObjectManager()->flush($action)
    }
}
}

【讨论】:

    猜你喜欢
    • 2015-01-30
    • 1970-01-01
    • 2012-05-08
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    • 2016-02-09
    相关资源
    最近更新 更多