0

I have a little problem, because I have to show json date with database in Symfony3.

My controller

/**
     * @Route("/api/rest", name="rest_api")
     * 
     * 
     * @Template
     */
public function indexAction(Request $Request) {

    $Repo = $this->getDoctrine()->getRepository('CommonUserBundle:Comment');
    $row = $Repo->findAll();


    $data = json_encode($row, true);

    return array(
        'comment' => $data
    );
}

And this is my layout in html.twig

{% for comments in comment %}
           {{ comments }}
{% endfor %}

But I don't know why nothing show. Help me please :)

3
  • Why do you want to encode it as json? Commented Jun 7, 2017 at 15:15
  • So are you trying to return json, or render a twig template? Commented Jun 7, 2017 at 15:15
  • This is my request to job. Commented Jun 7, 2017 at 15:17

3 Answers 3

1

Ok using my deductive skills (as your question is a bit vague) I am going to make the opposite assumption as everyone else did and say use the JSON helper function (Since 3.2).

return $this->json($myThings);

If you are working in older versions you need to return a proper Response object with the headers and such.

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

Comments

0

json_encode return a string.

Twig

{{ dump(comments) }}

Comments

0

try this:

  {% for comments in comment %}
       {{ comment }}
  {% endfor %}

If it doesn't work try to change and you want to print an array

$data = json_encode($row, true);

to $data = json_decode(json_encode($row), true);

if you want to print the string try this inside your twig

{{ dump(comments) }}

instead of this

{% for comments in comment %}
       {{ comment }}
  {% endfor %}

4 Comments

No he has @template annotation
ops sorry update answer with a new solution, thanks @goto
Yea, probalby I have to use object Response but I don't know how
When I use decode json I have error ,,Warning: json_decode() expects parameter 1 to be string, array given''

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.