1

This is how I create my array fields:

public function index($slug, Request $request, UserPasswordEncoderInterface $passwordEncoder)
  {
    $page = $this->getDoctrine()->getRepository(Pages::class)->findOneBy(['slug'=>$slug]);
    $fields =  (array) $page;
    return $this->render('mypage.html.twig', ['page' => $page, 'fields' => $fields]);
  }

The output is:

array:3 [▼
  "\x00App\Entity\Pages\x00id" => 3
  "\x00App\Entity\Pages\x00name" => "cat"
  "\x00App\Entity\Pages\x00color" => ""
]

But I actually need this result:

array:3 [▼
  "id" => 3
  "name" => "cat"
  "color" => ""
]

According to the suggestions I made this change:

public function index($slug, Request $request, UserPasswordEncoderInterface $passwordEncoder)
  {
    $page = $this->getDoctrine()->getManager()->getRepository(Pages::class)->findOneBy(['slug'=>$slug]);
    $fields =  get_object_vars($page);
    return $this->render('mypage.html.twig', ['page' => $page, 'fields' => $fields]);
  }

But this outputs me an empty array.

Stephan Vierkant
  • 9,674
  • 8
  • 61
  • 97
peace_love
  • 6,229
  • 11
  • 69
  • 157
  • 1
    Possible duplicate of [Doctrine entity object to array](https://stackoverflow.com/questions/25158549/doctrine-entity-object-to-array) – Maksym Fedorov Nov 26 '18 at 08:22
  • Possible duplicate of [Convert PHP object to associative array](https://stackoverflow.com/questions/4345554/convert-php-object-to-associative-array) – treyBake Nov 26 '18 at 08:43
  • 2
    Passing both your object and serialized object to your Twig template feels a bit unnecessary. To prevent a [X/Y Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem), please explain why you need this. – Stephan Vierkant Nov 26 '18 at 08:46
  • @StephanVierkant It is because it was a way I could finally solve this problem: https://stackoverflow.com/questions/53476565/how-can-i-get-all-fields-of-a-mysql-table-with-twig-symfony?noredirect=1#comment93823988_53476565 – peace_love Nov 26 '18 at 08:49
  • @StephanVierkant I could not loop through object properties. But through array I can. – peace_love Nov 26 '18 at 08:50

1 Answers1

6

You have two options:

1. Use Query::HYDRATE_ARRAY instead of findOneBy()

$query = $this->getDoctrine()
    ->getRepository(Pages:class)
    ->createQueryBuilder('p')
    ->getQuery();
$result = $query->getResult(Query::HYDRATE_ARRAY);

(stolen from this answer)

2. Use a Serializer

Use the Serializer Component or JMSSerializerBundle to serialize your entity object.

Stephan Vierkant
  • 9,674
  • 8
  • 61
  • 97
  • 3
    Worked with serializer! `$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new JsonEncoder()));$fields = $serializer->serialize($page, 'json');` – peace_love Nov 26 '18 at 08:47