Symfony2 entity invalid in 2.8.10+, but not 2.8.9

2019-07-24 04:21发布

问题:

This is a follow-up to this question: Symfony2: doing form validation before the form is posted I've been able to simplify the code to create an demo.

Basically, I'm trying to get the form to display the validation errors before receiving a real form submission from the browser/user. When I do this in <=2.8.9, the form is considered invalid and shows the validation errors. When I do this in >=2.8.10, the form is valid. But when sending the entity through the validator, it still finds violations (same as in 2.8.9).

I've created a demo/example repo: https://github.com/darrylhein/symfony_form_validation_issue_2.8

Am I doing something wrong?

Did the API change internally somehow since I'm using "undocumented" portions?

I'm first trying to validate that there's an issue before I submit a bug report. I'd submit a fix or test as well, but I'm not even sure where to start.

回答1:

The issue appears to be a change in the check to see if errors/violations can be added to a form. For some period of time (don't know how many versions) Symfony was allowing errors to unsubmitted forms and children, but in 2.8.10 this was changed with this commit: https://github.com/symfony/form/commit/498a795e875cbcb87511588e6619d5eb82c45f28

To work around this, I'm how retrieving the view data for each form field and passing that array into the submit method, as follows:

$fakeData = ['_token' => $token];
foreach ($form as $key => $value) {
    $fakeData[$key] = $value->getViewData();
}

$form->submit($fakeData);

I've also updated the repo: the commit.

Note: If you have data transformations on any of the fields, you may run into issues using the above code and you'll need to deal with them.