开发者

Trying to display multiple records from a single database in symfony 2

In the project I'm working on, I need to display 5 of the latest news articles on the website. In the Controller, I have written the following code:

      $news = $repository->createQueryBuilder('p')
          ->Where('p.contenttype = :type')
          ->setParameter('type', 'newsarticle')
          ->orderBy('p.lastedit', 'ASC')
          ->getQuery();

      $latestnews = $news->getResult();

This doesn't work for some reason, as I get the error message:

Item "url" for "Array" does not exist in "ShoutMainBundle:Default:page.html.twig" at line 34

However, when I change the getResult(); to getSingleResult(); it works, but will only display the one record (which is what I expect when I use that code).

This is where I come unstuck and confused about what I'm supposed to be doing. I have googled "how to display multiple records开发者_运维百科 in symfony" and I haven't found the answer. (If the answer has been out there, I apologise in advance for this). In normal PHP, I would expect to do a foreach loop (something similar anyway) to get the results which I need. But I also have a feeling that to achieve what I want I need to do something in Twig. But what I need to do I don't know.

Any help with this would be very much appreciated.

Thanks

Edit: Here is the template code that is used to display this:

            <section id="latestnews">
            <h2>Latest News</h2>
            <ul>
                <li><a href="..{{ news.url }}" title="Read {{ news.title }}" />{{ news.title }}</a></li>
            </ul>
        </section>


Your code tries to read from the variable news, and assumes that this variable has fields url and title. If your controller returns an array, you have to tread news as an array and iterate over it.

<section id="latestnews">
  <h2>Latest News</h2>
  <ul>
  {% for news in latestnews %}
   <li><a href="..{{ news.url }}" title="Read {{ news.title }}" />{{ news.title }}</a></li>
  {% endfor %}
  </ul>
</section>


It looks like in your template, you're looking for an object that's not found. It's looking for the url in an array object, but it doesn't exist. I think you need to put in a check, to see if that exists in the array, and then echo if it does. So something like if(news.url) echo news.url;

It may not be that exact syntax obviously, I'm not all that familiar with twig, but something similar to that.


You need to loop through the "news" results array in Twig.

{% for n in news %}

    <li><a href="..{{ n.url }}" title="Read {{ n.title }}" />{{ n.title }}</a></li>

{% endfor %}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜