Symfony2 PRE_SET_DATA $event->getData() 返回错误的对象

2022-01-04 00:00:00 events forms get php symfony

当我尝试从事件 PRE_SET_DATA 获取数据时,我得到了具有良好价值的对象,但我无法使用它.

When I try to get the data from event PRE_SET_DATA, I get my object with good value, but I can't use it.

这是我的测试代码:

        $builder->addEventListener(
        FormEvents::PRE_SET_DATA,
        function(FormEvent $event) use ($factory){

            $data = $event->getData();
            print_r($data);

        }
    );

这将返回一个长文本:

"YOUCommercantBundleEntityLivraisonChoix 对象 ( [id:YOUCommercantBundleEntityLivraisonChoix:private] => 22 ..."

"YOUCommercantBundleEntityLivraisonChoix Object ( [id:YOUCommercantBundleEntityLivraisonChoix:private] => 22 ..."

但是当我使用 getter 时:

But when I use a getter :

        $builder->addEventListener(
        FormEvents::PRE_SET_DATA,
        function(FormEvent $event) use ($factory){

            $data = $event->getData();
            print_r($data->getId());

        }
    );

我收到一个错误:

FatalErrorException:错误:调用非对象上的成员函数 getId()

FatalErrorException: Error: Call to a member function getId() on a non-object

我如何访问数据?

这适用于 PRE_BIND 事件.

This work fine for PRE_BIND event.

推荐答案

我需要在 getter 工作中使用这个条件:

I need to use this condition for the getter work :

        if ($data instanceof YOUCommercantBundleEntityLivraisonChoix) {

        }

相关文章