2017-06-29 24 views
1

我收到此錯誤,無法找出如何解決它。這個想法是列出用戶的所有書籍。用戶的ID調用時的路徑工作正常,例如:userbooks/4。但用用戶名userbooks/paul調用我得到這個錯誤「不可能訪問一個null變量的屬性(」用戶「)。」無法訪問空變量上的屬性(「用戶」)

<h2 > <a href="{{ path('userbooks',{'user' : entry.user}) }} ">{{ entry.title | title }}</a></h2>  

viewuserbookAction:

public function viewuserbooksAction($user) 
{ 
    $em = $this->getDoctrine()->getManager(); 

    $book = $em->getRepository('BookReviewBookBundle:Book')->find($user); 

    return $this->render('@BookReviewBook/Book/viewuserbooks.html.twig', 
     ['book' => $book]); 

} 

viewuserbook.html.twig

{% extends '@BookReviewBook/layout.html.twig' %} 
{% block title %}{% endblock %} 
{% block body %} 

    {% for book in book.user.entries %} 
    <h1>{{ book.title }} </h1> 
<div> 
<img class="img-valign" src="{{ asset('images/book/'~ book.path) }}" , style 
= "width:300px;height:300px;" class="img-thumbnail " /> 
<span class="text2">{{ book.author }}</span> 

{{ book.averageRating |rating }} 
</div> 
<hr class="style4"> 
<p>{{ book.summary|nl2br }} </p> 
<p><small>Posted by {{ book.user }} on {{ book.timestamp|date('H:i d/m/y') }} 
</small> 
</p> 
<hr class="style4"> 

{% endfor %} 

的routing.yml

userbooks: 
    path: /userbooks/{user} 
    defaults: { _controller: BookReviewBookBundle:User:viewuserbooks } 

    view: 
    path: /view/{id} 
    defaults: { _controller: BookReviewBookBundle:Book:view } 
    requirements: 
     id: \d+ 
+0

這可能是因爲您的圖書實體通過ID連接到用戶,而不是通過用戶名。 –

+0

你的代碼段中有很多'user'變量。究竟哪一個導致了這個錯誤? – DonCallisto

+0

@DonCallisto this path {{path('userbooks',{'user':entry.user})}}指向用戶名變量。可以將它改爲指向用戶標識嗎? – Suleiman

回答

0

謝謝大家的回覆和幫助。現在完美運作。不得不通過用戶名找到

viewuserbookAction:

public function viewuserbooksAction($username) 
{ 
    $em = $this->getDoctrine()->getManager(); 

    $book = $em->getRepository('UserBundle:User')->find($username); 

    return $this->render('@BookReviewBook/Book/viewuserbooks.html.twig', 
     ['user' => $book]); 

} 

viewuserbook.html.twig

{% extends '@BookReviewBook/layout.html.twig' %} 
{% block title %}{% endblock %} 


{% block body %} 


{% for book in user.entries %} 
<h1>{{ book.title }} </h1> 
<div> 
<img class="img-valign" src="{{ asset('images/book/'~ book.path) }}" , 
    style 
    = "width:300px;height:300px;" class="img-thumbnail " /> 
<span class="text2">{{ book.author }}</span> 

    {{ book.averageRating |rating }} 
    </div> 
    <hr class="style4"> 
    <p>{{ book.summary|nl2br }} </p> 
    <p><small>Posted by {{ book.user }} on {{ book.timestamp|date('H:i d/m/y') 
    }} 
    </small> 
    </p> 

    {% endfor %} 

    {% endblock %} 

的routing.yml

userbooks: 
    path: /userbooks/{username} 
    defaults: { _controller: BookReviewBookBundle:User:viewuserbooks } 

index.html.twig

<h2 > <a href="{{ path('userbooks',{ username : entry.user.id}) }} ">{{ 
    entry.title | title }}</a></h2>