简体   繁体   中英

Symfony/Doctrine: Validating ID of relation BEFORE symfony resolves it to an entity on form submission

class Thing {

    /*** loads of properties ***/

    /**
     * This is a many to many relation from Thing to Tags

     * @var \Doctrine\Common\Collections\Collection
     *
     * @Assert\All({
     *      @Assert\Uuid()
     * })
     */
    private $tags;

    /*** moar stuff ***/

}    

    /*** On the controller ***/

    protected function validateAndPersist(Request $request, AbstractEntity $entity, $successHttpCode)
    {
        $form = $this->createForm($this->getFormDefinition(), $entity);

        $form->submit($request);
        if ($form->isValid() === true) {
            $this->getDoctrineManager()->persist($entity);
            $this->getDoctrineManager()->flush();

            return $this->createView($entity, $successHttpCode);
        }

        return $form;
    }

So I have this entity above, which has a matching Symfony form and it's all tied up nicely by a controller. The payload coming in is meant to send an array of UUIDs on to the tags property. This works just fine, relations are saved correctly.

So there's some validation in place to make sure we're receiving an array of UUIDs.

Problem is, however, precisely when I'm not receiving an array of UUIDs. $form->submit() is trying to resolve the incoming IDs into actual tags via doctrine. The postgres database is complaining that it's not a valid UUID (the relevant field is of type guid), and I get a Doctrine error. It feels as if this is happening BEFORE form validation, or perhaps validation is not performed at all on this field because of the many to many relation.

Either way this results on a Doctrine\\DBAL\\DBALException on which the message includes details of the SQL query and whatnot and a big juicy 500 error:

    {
      "code": 500,
      "message": "An exception occurred while executing 'SELECT t0_.tag_id AS tag_id_0, t0_.name AS name_1 FROM tag t0_ WHERE t0_.tag_id IN (?)' with params [\"comedy\"]:\n\nSQLSTATE[22P02]: Invalid text representation: 7 ERROR:  invalid input syntax for uuid: \"comedy\""
    }

What I would obviously want is for validation defined on the entity to actually happen, as that would trigger a proper HTTP response without any boilerplate code to handle this specific case.

Any ideas?

Are you using another an embedded form for Tags in the main form? In this case, you need to set cascade_validation property to true on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM