简体   繁体   中英

Symfony2 Doctrine2 - how convert entity (not fetched form database) to array

I have entity from form framework.

    public function editAction($id)
    {
        $request = $this->getRequest();
        $r = $this->getProfileRepository();
        $profile = $id ? $r->find($id) : 
            new \Alden\BonBundle\Entity\Profile();
        /* @var $profile \Alden\BonBundle\Entity\Profile */
        $form = $this->createForm(
            new \Alden\BonBundle\Form\Type\ProfileType(), 
            $profile);
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
            ...

I need to convert $profile into array. In class Profile all properties are defined as private so I can't iterate like foreach($profile as $key => $value) {...}

You can use Reflection to retrieve class properties. Then, use a PropertyPath to retrieve properties values.

Here is an example:

$reflectedClass = new \ReflectionClass($yourClass);
$objectProperties = $reflectedClass->getProperties();
$datas = array();
foreach ($objectProperties as $objectProperty) {
    $property = $objectProperty->getName();

    $path = new PropertyPath($property);
    $datas[] = $path->getValue($object);
}

But, if your form / entity is simple, you can just create a dedicated method in entity to return the right array.

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