Symfony2的新增功能;我現在使用FOSUserBundle作爲我的用戶提供者。因爲它不爲刪除操作提供一個控制器,我寫我自己:Symfony2:FOSUserBundle刪除操作錯誤
/**
* Delete user
*
* @param integer $id
*
* @Route("/delete/{id}")
*
* @return RedirectResponse
*/
public function deleteAction($id)
{
$em = $this->getDoctrine()->getManager();
$um = $this->get('fos_user.user_manager');
$user = $um->findUserBy(array(
'id' => $id
)
);
$em->remove($user);
$em->flush();
return new RedirectResponse("star9988_user_user_index");
}
而且從我的模板添加了一個鏈接路徑:
<a href="{{ path('star9988_user_user_delete', {'id': user.id}) }}">
我最初試圖傳遞中的ObjectManager ,通過ID查詢User對象,然後使用deleteUser方法刪除它,但出於某種原因,它不會讓我使用通常的構造函數注入方法來獲取ObjectManager。
因此,我採取了調用EntityManager,並在我的$ user對象上調用它的remove()方法。
結果很奇怪:當我用SequelPro檢查我的數據庫時,我注意到指定的用戶對象確實被刪除了。但是,瀏覽器返回此錯誤:
EntityManager#remove() expects parameter 1 to be an entity object, NULL given.
任何幫助將不勝感激。
編輯:
I have changed my code to the following:
/**
* Delete user
*
* @param integer $id
*
* @Route("/delete/{id}")
*
* @return RedirectResponse
*/
public function deleteAction($id)
{
$em = $this->getDoctrine()->getManager();
/** @var \Star9988\ModelBundle\Entity\User $user */
$user = $this->getDoctrine()->getRepository('ModelBundle:User')->find($id);
$em->remove($user);
$em->flush();
return new RedirectResponse("star9988_user_user_index");
}
奇怪的是,我得到了相同的結果:實體從數據庫中刪除。
看來我的路由沒有通過參數出於某種原因。
DEBUG - SELECT t0.username AS username1, t0.username_canonical AS username_canonical2, t0.email AS email3, t0.email_canonical AS email_canonical4, t0.enabled AS enabled5, t0.salt AS salt6, t0.password AS password7, t0.last_login AS last_login8, t0.locked AS locked9, t0.expired AS expired10, t0.expires_at AS expires_at11, t0.confirmation_token AS confirmation_token12, t0.password_requested_at AS password_requested_at13, t0.roles AS roles14, t0.credentials_expired AS credentials_expired15, t0.credentials_expire_at AS credentials_expire_at16, t0.id AS id17, t0.FirstName AS FirstName18, t0.LastName AS LastName19, t0.creditLimit AS creditLimit20, t0.creditAvailable AS creditAvailable21, t0.accountBalance AS accountBalance22, t0.rebate AS rebate23, t0.parent AS parent24 FROM StarUsers t0 WHERE t0.id = ? LIMIT 1
FOSUserBundle附帶一個用戶管理器https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Doctrine/UserManager.php#L49,它可以讓你做到這一切:https://github.com/ FriendsOfSymfony/FOSUserBundle/BLOB /主/資源/ DOC/user_manager.md – 2015-02-10 12:23:01