how to get the type of a doctrine entity property

后端 未结 4 694
温柔的废话
温柔的废话 2021-01-06 04:09

Actually I have a doctrine entity that I need to fill its prperties dynamically.

I\'d like to be able to do something like this:

$entity = new Entity         


        
4条回答
  •  执念已碎
    2021-01-06 04:52

    Old as it is, this post was really useful when we needed a workaround for boolean fields being always set to true in some contexts -- thank you smarber and yoshi. Our workaround detects boolean fields (in PATCH, in this case) and uses the corresponding setter to propagate the value. (Of course, it would be nice if this weren't necessary.)

    /*
     * @PATCH("/entity/{name}")
     */
    public function patchEntityAction(Request $request, $entity)
    {
        ...
    
        $form->handleRequest($request);
    
        $manager = $this->getDoctrine()->getManager();
    
        // handle booleans
        $metadata      = $manager->getClassMetadata($bundle_entity);
        $entity_fields = $metadata->getFieldNames();
        foreach ($entity_fields as $field) {
            $type = $metadata->getTypeOfField($field);
            if ($request->request->has("$field") && $type == 'boolean') {
                $setter = 'set' . ucfirst($field);
                $entity->$setter(!!$request->request->get("$field"));
            }
        }
    
        $manager->persist($entity);
        $manager->flush();
    
        ...
    
    }
    

    Ref: https://api.symfony.com/3.4/Symfony/Component/HttpFoundation/Request.html

提交回复
热议问题