Search code examples
phpsymfonysymfony-formssymfony5

Symfony Form Validation not working in Edit


Form Validation only works in new but not in edit even though both use the same Form (error below). Am I using form validation wrong?

Demo repo: https://github.com/rwkt/demo-dynamicform

  1. Create a new post with a title; 2. Edit the post to remove the title and save.

Error

Expected argument of type "string", "null" given at property path "title".

exception screenshot


Solution

  • Your setter requires string,not ?string (string or null). So it is RQUIRED to pass it string (not null). Validation works after populating the object, so it first calls setTitle, then it validates. But since you filled nothing, it calls setTitle(null) and php throws error before validator validates the data.

    Refactor your setter to setTitle(?string)