2012-05-24 86 views
1

我有兩個實體UserRole。兩者都用於Symfony2進行身份驗證。認證過程需要在返回數組的類User中有方法'getRoles'。 另一方面,表單構建器需要角色作爲集合。 我如何強制表單生成器使用特定的getter來獲取角色的集合?symfony2多對多實體形式

class UserType extends AbstractType{ 
//... 
->add('roles', 'entity', array('class' => 'MyBundle:Role', 
            'property' => 'name', 
            'required' => false, 
            'multiple' => true, 
            'expanded' => true, 
            ); 

//... 
    } 


class User implements UserInterface { 
//... 
    public function getRoles() { 
    return $this->roles->toArray(); //This needs authentication mechanism 
    } 

public function getRolesCollection() { 
    return $this->roles;   //This needs form builder. 
} 
//... 
} 
+0

你爲什麼不換呢?邏輯上getRoles應該返回集合。我不明白你爲什麼首先要做 - > toArray。什麼是用例? – Flukey

+0

這是因爲Symfony的身份驗證過程需要數組正常工作。沒有 - > toArray它拋出異常'可捕獲的致命錯誤:參數4傳遞給Symfony \ Component \ Security \ Core \ Authentication \ Token \ UsernamePasswordToken :: __ construct()必須是一個數組, –

回答

0

也許你可以嘗試顛倒了一切:

class UserType extends AbstractType{ 
//... 
->add('rolesCollection', 'entity', array('class' => 'MyBundle:Role', 
            'property' => 'name', 
            'required' => false, 
            'multiple' => true, 
            'expanded' => true, 
            ); 

//... 
    } 


class User implements UserInterface { 
    protected $rolesCollection 
//... 
    public function getRoles() { 
    return $this->rolesCollection->toArray(); //This needs authentication mechanism 
    } 

public function getRolesCollection() { 
    return $this->rolesCollection;   //This needs form builder. 
} 
//... 
}