Search code examples
phpformssymfonysymfony4

Symfony4 stop handleRequest() from removing values of my object


I am submitting a form and in my controller I use handleRequest to validate the form.

Lets say I try to update my object name 'object' - It has an id, name and color field.

On the same page I also show a lost with the names of all my objects that I fetch from the database

Here is my code:

$object = self::getObjectById($objectId);

$objects = self::getAllObjects();

$objectForm = self::CreateObjectForm($object);

$objectFormForm->handleRequest($request);

dd($objects);

When I submit the form and I leave the name field open, It throws an error that the field is required when it reloads the page, the name field of the form is still empty which is normal.

But here is the problem, in the list of objects that is also showing on this page the name of the object I tried to update has no name showing anymore in this list.

I don't know why this is happening since I fetched this list of objects completely separately from the form object. When I dd() the objects after the handleRequest() I cans see in the dumped vars that indeed the name field is empty. When I check the database, the name field is not empty and still holds the old name. Which makes sense because the object is not persisted and flushed to de db. When I dd() the same list before the handleRequest() everything is normal.

How can I prevent this behavior? And why is this happening?


Solution

  • I don't know why this is happening since i fetched this list of objects completely seperatly from the form object.

    It's referencing the same entity which get's dumped in it's current, live, dirty state as submitted by the form.

    If you need to render the clean, persisted values then you just need to store them in a variable as a string instead of as the object, and before handling the request.

    Try something like this:

    $object = self::getObjectById($objectId);
    
    $objects = self::getAllObjects();
    
    $persistedObjects = [];
    foreach($objects as $obj){
      $persistedObjects[$obj->getId()] = $obj->getName();
    }
    
    $objectForm = self::CreateObjectForm($object);
    
    $objectFormForm->handleRequest($request);
    
    dd($persistedObjects);