Fernando André
Fernando André

Reputation: 1213

PHP and Symfony object to array conversion by type cast

I'm using symfony2 and createForm to get the http post data. After witch I do:

$Data = (array) $form->getData();

And I get:

array (size=1)
  '�Far\MT\AccountBundle\Entity\Movement�toAccount' => int 3

I don't think this is the normal behavior for these cases, any sugestions?

the toAccount should be the complete index name.

Wasn't able to reproduce the conditions in a test case for the cli:

<?php

namespace A;

class MyClass
{
    public $id;
    public $name;
    public $age;
}

$object = new MyClass();
$object->name = "Andre";
$object->id   = 1;
$object->age  = 30;

var_dump($object);

$Ar = (array) $object;
var_dump($Ar)

This above worked ok.

I used this solution:

//comment
$Data = $form->getData();
$obj = new \ReflectionObject($Data);
$props = $obj->getProperties();

$propname = array();
foreach ($props as $prop) {

    $tmp = "get".ucfirst($prop->name);

    if (($res = $Data->$tmp() )!== null) {
        $propname[$prop->name] = $res;
    }
}
$tmpSearch = $propname;

I'll clean it up after.

Upvotes: 0

Views: 11317

Answers (1)

le0diaz
le0diaz

Reputation: 2508

You can use the Symfony normalizer class, as your propose will fail when you have fields in your form name with underscore like 'facility_id' but your setter is called facilityId

<?php
$data = $form->getData();       
$normalizers = new \Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer();
$norm = $normalizers->normalize($data);
print_r($norm);

you'll get output like

Array ( [fullname] => fullnameVal [email] => [email protected] [phoneNumber] => 5554444 [facilityId] => 123132 )

Upvotes: 2

Related Questions