Symfony 3找不到对象错误

时间:2017-08-04 15:49:12

标签: php symfony doctrine twig

我正在建立一个博客,并希望主页显示最新的博客条目,包括指向单个条目的链接。 我得到了列表中显示的所有条目的链接,但我无法弄清楚如何显示单个条目。此外,一旦我尝试点击链接,我总是会收到“找不到对象”的异常。 这是控制器,它将函数内容显示为单个条目:

<?php
// src/BlogBundle/Controller/BlogController.php
namespace BlogBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use BlogBundle\Entity\Blog;
use BlogBundle\Entity\User;
use BlogBundle\Form\BlogType;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class BlogController extends Controller
{
  /**
       * @Route("/blog", name="bloglist", requirements={"page": "\d+"})
       */
    public function listAction()
    {
        $entry = $this->getDoctrine()->getRepository('BlogBundle:Blog')->findBy(array(), array('date' => 'DESC'));
        dump($entry);
         return $this->render('BlogBundle:blog:blog.html.twig', [
           'bloglist' => $entry
         ]);
    }
    /**
    * @Route("/blog/new", name="create")
    */
    public function createAction(Request $request) {
      $entry = new Blog();
      $entry->setDate(new \DateTime('now'));
      $entry->setAuthor($this->getUser());
      $form = $this->createForm(BlogType::class, $entry);
      $form->handleRequest($request);

      if ($form->isSubmitted() && $form->isValid()) {

        $entry = $form->getData();
        $em = $this->getDoctrine()->getManager();
        $em->persist($entry);
        $em->flush();
        return $this->render('BlogBundle:blog:createsubmit.html.twig', array(
          'entry' => $entry,
          'form' => $form->createView(),
          'success' => true
        ));
      }

      return $this->render('BlogBundle:blog:new.html.twig', array(
        'quote' => 'New blog entry created!',
        'form' => $form->createView(),
      ));
    }
    /**
     * @Route("/blog/singleentry/{id}", name="singleentry", requirements={"id" = "\d+"}, defaults={"id" = 0})
     */
    public function listSingleEntryAction(Request $request, Blog $blog)
    {
      $em = $this->getDoctrine()->getRepository('BlogBundle:Blog')->find($blog);
      $form = $this->createForm(BlogType::class, $entry);
     $form->handleRequest($request);
     $em->persist($entry);
     $em->flush();

         return $this->render('BlogBundle:singleentry:edit.html.twig', array(
           'entry' =>$entry,
           'form' => $form->createView()
         ));
       }


    /**
    * @Route("/blog/edit/{id}", name="entryedit", requirements={"id" = "\d+"}, defaults={"id" = 0})
    *
    */
    public function editAction(Request $request, Blog $blog) {
       $em = $this->getDoctrine()->getManager();
       $entry = $em->getRepository('BlogBundle:Blog')->find($blog);
      if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN') || $entry->getAuthor() == $this->getUser()->getUsername() ) {

        $form = $this->createForm(BlogType::class, $entry);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

          $em->persist($entry);
          $em->flush();

          return $this->render('BlogBundle:blog:editsubmit.html.twig', array(
            'entry' => $entry,
            'form' => $form->createView(),
            'success' => true
            ));
          }

          return $this->render('BlogBundle:blog:edit.html.twig', array(
            'form' => $form->createView(),
          ));
        }

      else {
        echo '<div class="alert alert-danger alert-dismissable">
        <span aria-hidden="true" data-dismiss="alert" class="close">×</span>
        <h4>
        <i class="fa fa-exclamation-circle "></i>
        Only the author of an entry is allowed to edit it!</h4></div>';

        return $this->listAction();
      }
    }
    /**
    * @Route("/blog/delete/{id}", name="entrydelete", requirements={"id" = "\d+"}, defaults={"id" = 0})
    *
    */
    public function deleteAction(Request $request, Blog $blog) {
       $em = $this->getDoctrine()->getManager();
       $entry = $em->getRepository('BlogBundle:Blog')->find($blog);
      if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN') || $entry->getAuthor() == $this->getUser()->getUsername() ) {
          $em->remove($entry);
          $em->flush();
          return $this->render('BlogBundle:blog:deletesubmit.html.twig');
        }
      else {
        return $this->render('BlogBundle:blog:error.html.twig');
      }
    }
    public function configureOptions(OptionsResolver $resolver) {
      $resolver->setDefaults([
        'data_class' => 'BlogBundle\Entity\Blog'
      ]);
    }
}
?>

我的主页:

<?php

namespace BlogBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;


class DefaultController extends Controller {
  /**
  * @Route("/", name="welcome")
  */
  public function indexAction() {
    $entry = $this->getDoctrine()->getRepository('BlogBundle:Blog')->findBy(array(), array('date' => 'DESC'),5);
    dump($entry);
    return $this->render('BlogBundle:Default:index.html.twig', [
        'Welcome'    => 'Welcome!',
        'avatar_url' => 'http://www.lufthansa.com/mediapool/jpg/45/media_789050645.jpg',
        'blog'       => $this->redirectToRoute('singleentry'),
        'bloglist'   => $entry
          ]);
  }
}
?>

这些是我尝试渲染的树枝模板

singleentry.html.twig:

{% extends '::base.html.twig' %}

{% block body %}

<div class="container">
    <div class="col-md-11">
          <h1 class="page-header">{{ blog. title }}</h1>
      <div class="table">
            <p><span class="fa fa-clock-o"></span> Posted on {{ blog.date|date('d.M Y H:i A') }} </p>
            <p><span class="fa fa-user-circle"></span> Posted by {{ blog.author }} </p>
            <p>{{ blog.text }}</p>
            <!-- <a class="btn btn-primary" href="#">Read More <span class="glyphicon glyphicon-chevron-right"></span></a> -->
            <button type="button" class="btn btn btn-info">
              <a href="{{ path('entryedit', {'id':blog.id}) }}" style="color: #FEFEFE">Edit entry</a>
            </button>
            <button type="button" class="btn btn btn-warning">
              <a href="{{ path('entrydelete', {'id':blog.id}) }}" style="color: #FEFEFE">Delete entry</a>
            </button>
            <hr>
      </div>
    </div>
</div>
{% endblock %}

我的主页上的博客条目列表:

<div class="panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title text-center">My latest blog entries</h3>
  </div>
  <table class="table">
    {% for blog in bloglist %}
          <tr>
              <td><a href="{{ path('singleentry') }}">{{ blog.title }}</a></td>
              <td width="85%" style="max-width: 0;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;">
              {{ blog.text }}
              </td>
          </tr>
      {% endfor %}
       </table>
</div>

已编辑版本的listSingleEntryAction - &gt;对象显示为NULL

public function listSingleEntryAction(Request $request, $id)
{
  $em = $this->getDoctrine()->getManager();
  $entry = $em->getRepository('BlogBundle:Blog')->find($id);
  if($entry == null)
  {
      $message='Entry does not exist';
      return $this->render('BlogBundle:blog:error.html.twig');
  }
  return $this->render('BlogBundle:blog:singleentry.html.twig', Array(
      'entry' => $entry,
      'success' => true,
  ));


   }

2 个答案:

答案 0 :(得分:0)

问题是你的论点。

public function listSingleEntryAction(Request $request, Blog $blog)
    {

首先,它不应该是博客类型。它是int。 其次,将其重命名为$ id。

我认为编辑和删除操作存在同样的问题。

答案 1 :(得分:0)

检查你的行动。前两行是你遇到问题的原因。

 /**
     * @Route("/blog/singleentry/{id}", name="singleentry", requirements={"id" = "\d+"}, defaults={"id" = 0})
     */
    public function listSingleEntryAction(Request $request, Blog $blog)
    {
      $em = $this->getDoctrine()->getManager();
      $entry = $em->getRepository('BlogBundle:Blog')->find($blog);