Which is the suggested place to modify binded form data in Symfony?

自闭症网瘾萝莉.ら 提交于 2019-11-30 10:52:11

问题


I've a form for creating a new Customer. A customer may have a mobile number. Mobile number should be persisted without + or 00 prefix that user can type. This can be accomplished easly with:

$customer->setMobile(preg_replace("/^(\+|00)/", '', $customer->getMobile()));

Which is the best place to put this code?

  • Inside a CustomerController prior to call entity manager and persist the entity. Is this really a matter of a controller in MVC pattern?
  • Using a SanitizeCustomerSubscriber and listening to FormEvents:POST_BIND event
  • Using a CustomerSanitizer service

Any other idea? Of course i'm speaking of data manipulation in general, mobile number is just an example: fields to be sanitized could be more than just one.


回答1:


You should do this in the PRE_BIND event, where you can access the submitted data before it is being processed.

$builder->addEventListener(FormEvents::PRE_BIND, function (FormEvent $event) {
    $data = $event->getData();
    if (isset($data['mobile'])) {
        $data['mobile'] = preg_replace("/^(\+|00)/", '', $data['mobile']);
    }
    $event->setData($data);
});

For the record, as of Symfony 2.3, this event is called PRE_SUBMIT.




回答2:


I'd put this into the Customer setMobile() method — the closer to the data itself, the better. This way the mobile number will be sanitized no matter what controllers or forms are used to set it.



来源:https://stackoverflow.com/questions/11697560/which-is-the-suggested-place-to-modify-binded-form-data-in-symfony

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!