2012-04-12 14 views
1

私はSymfony 1.4を使用しました。今私はsymfonyの2.学ぶ私が行いますhttp://symfony.com/doc/current/book/doctrine.html と私が持っている:私は使用することができますforeachの中TWIGとの関係

symfony 1.4で
class Product 
{ 

    /** 
    * @ORM\ManyToOne(targetEntity="Category", inversedBy="products") 
    * @ORM\JoinColumn(name="category_id", referencedColumnName="id") 
    */ 
    protected $category; 

    //... 
} 

class Category 
{ 

    /** 
    * @ORM\OneToMany(targetEntity="Product", mappedBy="category") 
    */ 
    protected $products; 

    public function __construct() 
    { 
     $this->products = new ArrayCollection(); 
    } 
    //... 
} 

:私は取得できますか

$result = findAll from Products. 
foreach ($results as $result){ 
    echo $result->getCategory()->getName(); 
} 

TWIGシステムとの関係(この例ではCategory)

{% for item in results %} 
       <li><a href="{{ item.id }}">{{ item.name }} --- {{ item.category }} {{item.category.name}}</a></li> 
      {% endfor %} 

item.categoryとitem.category.nameは機能しません。私はこれをドキュメントで見つけることができません。

EDIT:

OK、私が今知っています。私は1つの製品に関係がありません。どのように私はこれ前に保護することができますか?

私が持っている:各行カテゴリ内の

id | name | category 
1 | first | 1 
2 | second | NULL 
3 | third | 2 

場合は、この作業OK nullではありませんが、私は関係でNULL持っているならば、私はエラーを持っている:

私が作ることができますどのような
Item "name" for "" does not exist in AcmeStoreBundle:Default:index.html.twig at line 3 

これとともに?

+0

あなたの関係で何かが壊れているようです。私は似たようなことがあり、 '{{article.user.name}}'はうまく動作します。 – KingCrunch

+0

あなたの例はどこですか? :) –

+0

どのような例ですか?私はあなたの '{{item.category.name}}'がうまく動作していると私は思っています。あなたの問題は以前のどこかにあるはずです。 – KingCrunch

答えて

3

名前を出力する場所にこれを追加します。これにより、小枝がそのエラーを投げるのを防ぎます。

{% if item.category.name is defined %} 
    {# print the name here #} 
{% endif %}