首页 > 解决方案 > 如何访问最初提交的 Symfony 表单数据?

问题描述

我正在使用一些 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)
        }
    ]
]

标签: symfonysymfony-forms

解决方案


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

1) 直接取自 Request

$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();
});

推荐阅读