我如何访问Symfony表单的原始提交数据?

问题描述 投票:0回答:1

我正在使用某些Symfony表单,需要访问最初提交的(未修改的)数据。数据访问器方法$form->getData()$form->getViewData()$form->getModelData()都为我提供了已转换的值,但是我需要PRE_SUBMIT事件中的数据。

我可以编写一个侦听器并将其提取到PRE_SUBMIT上,但是随后我必须将此信息存储在任何位置,并在使用该表单的服务中访问它。现在,我的服务仅看到传递的表单对象,并且没有其他依赖项即可工作。

其他解决方法涉及读取请求对象。看起来不是一个明智的选择,因为该表单可能是从其他来源填充​​的(例如会话,它是一个过滤器表单)。

是否有一种“官方”方法可以直接从表单对象访问原始提交的数据?如果没有,是否值得进行功能请求?有什么意见吗?

(我的用例是一个过滤器表单,其中状态存储在会话中并从会话中检索。由于表单可以在提交时不包含来自涉及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)
        }
    ]
]
symfony symfony-forms
1个回答
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();
});
© www.soinside.com 2019 - 2024. All rights reserved.