如何访问最初提交的Symfony表单数据?

时间:2018-06-05 14:15:15

标签: symfony symfony-forms

我正在处理一些Symfony表单,需要访问最初提交的(未触及的)数据。数据访问器方法$form->getData()$form->getViewData()$form->getModelData()都为我提供了已经转换的值,但我需要PRE_SUBMIT事件中的数据。

我可以编写一个监听器并在PRE_SUBMIT上提取它们,但随后我必须将这些信息存储在任何地方并在我使用该表单的服务中访问它。现在,我的服务只看到传递的表单对象,并且没有其他依赖项。

其他解决方法涉及从请求对象中读取。看起来不像是一个聪明的选项,因为表单可以从其他来源填充​​(如会话,它是一个过滤形式)。

是否有#34;官员"直接从表单对象访问最初提交的数据的方法?如果没有,是否值得功能请求?有什么意见吗?

(我的用例是一种过滤形式,其中状态存储在会话中并从会话中检索。由于表单可以在没有来自请求的数据的情况下提交,涉及HTML-POST,HTML-GET和JSON-POST的模式,我不想只存储请求数据。)

编辑2018-06-07:根据评论中的要求,我提供了一个代码示例:

/**
 * handles the filterForm request reading POST-data or namespaced JSON payload with POST method or any standard form request
 *
 * @param FormInterface $filterForm
 * @return void
 * @throws ResponseException
 */
public function handleRequest(FormInterface $filterForm): void
{
    // reset the filter state in the session, if a reset_filter query parameter was set
    if (true === $this->request->query->getBoolean('reset_filter', false)) {
        $this->setFilterState(null, $this->request->attributes->get('_route'));
        $this->filterIsActive = true;
    }

    // handle filter submission in json context
    if ($this->request->isMethod('POST') && $this->request->attributes->get('_format') === 'json') {
        if ($this->request->get($filterForm->getName())) {
            $submitData = $this->request->get($filterForm->getName());
        }
        else {
            $postData = JsonHelper::parseAndCheckJsonPostData($this->request);
            if ($postData instanceof Response) {
                throw new ResponseException($postData);
            }
            $submitData = $postData[$filterForm->getName()] ?? null;
        }
        if (null !== $submitData) {
            dump($submitData);
            $filterForm->submit($submitData, true);
            dump($filterForm->getData());
        }
    }
    else {
        // @todo find a smooth way to get the original submitted data of a form, when it is handled by the default handleRequest()-menthod
        $submitData = null;
        $filterForm->handleRequest($this->request);
    }

    // load the filter state from the session and submit it, if it is not yet set and we are in HTML context
    if (!$filterForm->isSubmitted()
        && $this->request->attributes->get('_format') === 'html'
        && null !== $this->getFilterState($this->request->attributes->get('_route'))
    ) {
        $filterForm->submit($this->getFilterState($this->request->attributes->get('_route')));
    }

    if ($filterForm->isSubmitted()) {
        $this->filterIsActive = true;

        // return an JSON error-document, if the filter form is not valid
        if (!$filterForm->isValid() && $this->request->attributes->get('_format') === 'json') {
            throw new ResponseException(
                new JsonResponse([
                    'type' => 'error',
                    'message' => $this->translator->trans('Form.Filter.errorMessage'),
                    'filterForm' => $this->serializer->normalize($filterForm->createView()),
                ], Response::HTTP_BAD_REQUEST)
            );
        }

        // store the new filter state, if filter is active and and valid
        if ($filterForm->isValid() && null !== $submitData) {
            $this->setFilterState($submitData, $this->request->attributes->get('_route'));
        }
    }
}

输出:

array:4 [▼
    "singleEntity" => "1"
    "multipleEntities" => array:1 [▼
        0 => "1"
    ]
    "dateRange" => array:2 [▼
        "left_date" => "06.06.2018"
        "right_date" => "07.06.2018"
    ]
    "submit" => true
]

array:11 [▼
    "singleEntity" => MySingleEntity {#3739 ▶}
    "facilities" => ArrayCollection {#3419 ▼
        -elements: array:1 [▼
            0 => MyMultiEntity {#3799 ▶}
        ]
    }
    "createdOrUpdatedBetween" => array:2 [▼
        "left_date" => DateTime @1528236000 {#3408 ▼
            date: 2018-06-06 00:00:00.0 Europe/Berlin (+02:00)
        }
        "right_date" => DateTime @1528322400 {#3397 ▼
            date: 2018-06-07 00:00:00.0 Europe/Berlin (+02:00)
        }
    ]
]

1 个答案:

答案 0 :(得分:0)

我有两个选择如何保存提交的数据

1)直接从请求中获取

$submitted_data = [];
foreach ($form->all() as $child) {
    if ($request->request->has($child->getName())) {
        $submitted_data[$child->getName()] = $request->request->get($child->getName());
    }
}

2)使用表单事件

$submitted_data = null;
$formBuilder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use (&$submitted_data) {
    $submitted_data = $event->getData();
});