SonataAdminBundle中的Symfony preUpdate事件

时间:2016-08-22 09:34:47

标签: symfony doctrine-orm sonata-admin sonata

我有带有字段的产品实体

  • name,
  • purch_price_net
  • purch_price_gross
  • purch_vat_value
  • purch_vat_rate_id [来自其他表]

我需要功能,当用户在SonataAdminBundle purch_price_net字段中进行修改时,purch_price_gross [和其他字段]会自动更改其值。

所以我创建了PreUpdateProducts监听器:

    <?php

    namespace AppBundle\EventListener;

    use Doctrine\ORM\Events;
    use AppBundle\Entity\Products;

    // echo Events::preUpdate;
    class PreUpdateProducts {
        public function preUpdate(PreUpdateEventArgs $eventArgs) {
            if ($eventArgs->getEntity () instanceof Products) {
                if ($eventArgs->hasChangedField ( 'purchPriceNet' )) {
                    $newPurchPriceNet = $eventArgs->getNewValue ( 'purchPriceNet' );


                    $eventArgs->setNewValue ( 'purchPriceGross', $newPurchPriceNet * 1.23 );
                    $eventArgs->setNewValue ( 'name', 'changedName' ); // for tests
                }
            }
        }
    }

并在services.yml中添加:

services:
[...]

    my.listener:
        class: AppBundle\EventListener\PreUpdateProducts
        tags:
            - { name: doctrine.event_listener, event: PreUpdateProducts }

不幸的是,它没有起作用,按下&#39;更新后,没有任何改变[除了purchPriceNet]。 我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:1)

好的,谢谢。

我是这样做的:

在Products类中添加了注释:

* @ORM\EntityListeners({"AppBundle\EventListener\PreUpdateProduct"})

和我的PreUpdateProduct类看起来像:

<?php

namespace AppBundle\EventListener;

use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Entity\Products;
class PreUpdateProduct {

    /**
     * @ORM\PreUpdate
     */
    public function preUpdate(Products $product, PreUpdateEventArgs $event) {
        if ($event->getEntity () instanceof Products) {
            if ($event->hasChangedField ( 'purchPriceNet' )) {
                $newPurchPriceNet = $event->getNewValue ( 'purchPriceNet' );
                $purchVatRateObj=$product->getPurchVatRate();
                $purchVatRate=$purchVatRateObj->getVatRate();
                $purchVatValue=$newPurchPriceNet*$purchVatRate;
                $product->setPurchVatValue($purchVatValue);
                $product->setPurchPriceGross ( $newPurchPriceNet +$purchVatValue );
            }
            if ($event->hasChangedField ( 'sellPriceGross' )) {
                $newSellPriceGross = $event->getNewValue ( 'sellPriceGross' );
                $sellVatRateObj=$product->getSellVatRate();
                $sellVatRate=$sellVatRateObj->getVatRate();
                $sellPriceNet=$newSellPriceGross/(1+$sellVatRate);
                $sellVatValue=$newSellPriceGross-$sellPriceNet;
                $product->setSellVatValue($sellVatValue);
                $product->setSellPriceNet ( $sellPriceNet);
            }
        }
    }
}

现在可行。

相关问题