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.

5
  • 1
    Possible duplicate of Doctrine entity object to array Commented Nov 26, 2018 at 8:22
  • Possible duplicate of Convert PHP object to associative array Commented Nov 26, 2018 at 8:43
  • 2
    Passing both your object and serialized object to your Twig template feels a bit unnecessary. To prevent a X/Y Problem, please explain why you need this. Commented Nov 26, 2018 at 8:46
  • @StephanVierkant It is because it was a way I could finally solve this problem: stackoverflow.com/questions/53476565/… Commented Nov 26, 2018 at 8:49
  • @StephanVierkant I could not loop through object properties. But through array I can. Commented Nov 26, 2018 at 8:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Worked with serializer! $serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new JsonEncoder()));$fields = $serializer->serialize($page, 'json');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.