dongxi1965 2015-07-09 19:34
浏览 41

如何使用定义为服务的表单将数组数据映射到Symfony2实体?

I need to map data coming in the form of an array to an entity. The data does not come from a request, but is fetched from a remote source by the application.

I want to use a form to map the data to an entity. This is how I instantiate the form as a service and pass it to my custom class (ApiResponseMapper):

book_form_type:
    class: Air\BookishBundle\Form\Type\BookType
    name:
        - { name: form.type, alias: book_type }

book_form:
    factory_service: form.factory
    factory_method: create
    class: Symfony\Component\Form\Form
    arguments: [@book_form_type]

api_response_mapper:
    class: Air\BookishBundle\Lib\ApiResponseMapper
    arguments: [@bestseller_list_form, @book_form]

In ApiResponseMapper, I want to be able to map the data into the array:

public function mapResponse($response)
{
    $form = $this->bookForm; // bookForm is a now a memeber of this class.
    $form->submit($response);

}

This will not map the $response (array data) to my Book entity (the bookForm has Book class set as the data_class). I'm starting with Symfony, and I'm really not sure how I can use this form to map the $response. The 'traditional' method would be to call something like this in a controler: $form = $this->createForm(new BookType(), $Book);, but as you can see, this case is different.

I need to bypass handleRequest() and call submit() manually. How do I map the data onto the entity in this scenario?

  • 写回答

1条回答 默认 最新

  • douyan6742 2015-07-09 20:18
    关注

    Well, the solution was rather simple. Maybe it will help somebody out in the future. My method looks like this:

    public function mapResponse($response)
    {
        $Book = new Book();
        $form = $this->bookForm;
        $form->setData($Book);
        $form->submit($response);
        return $Book;
    }
    

    The class being mapped onto should be instantiated and passed as a parameter to setData() called on the form object. Notice that this particular example does not leverage data validation with the form.

    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c