Created
June 19, 2011 14:05
-
-
Save avanwieringen/1034319 to your computer and use it in GitHub Desktop.
Symfony2 Form Component + Doctrine2 CRUD problems
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Ingenii\HomeBudgetBundle\Controller; | |
use Symfony\Bundle\FrameworkBundle\Controller\Controller; | |
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; | |
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; | |
class DashboardController extends Controller | |
{ | |
/** | |
* @Route("/", name="homebudget_dashboard_index") | |
* @Template() | |
*/ | |
public function indexAction() | |
{ | |
return array(); | |
} | |
/** | |
* @Route("/user/{id}", name="homebudget_dashboard_useroverview", defaults={"id" = null}, requirements={"id" = "\d+"}) | |
* @Template() | |
*/ | |
public function userOverviewAction($id) | |
{ | |
$em = $this->get('doctrine')->getEntityManager(); | |
if(null === $id) { | |
$user = new \Ingenii\HomeBudgetBundle\Entity\User(); | |
} else { | |
$user = $em->find('IngeniiHomeBudgetBundle:User', $id); | |
} | |
$form = $this->getUserForm($user); | |
$users = $em->getRepository('IngeniiHomeBudgetBundle:User')->findAll(); | |
return array('user' => $user, 'users' => $users, 'form' => $form->createView()); | |
} | |
/** | |
* @Route("/user/delete/{id}", name="homebudget_dashboard_userdelete") | |
*/ | |
public function userDeleteAction($id) { | |
die("Deleted " + $id); | |
} | |
/** | |
* @Route("/user/submit", name="homebudget_dashboard_usersubmit") | |
*/ | |
public function userSubmitAction() { | |
$request = $this->get('request'); | |
$em = $this->get('doctrine')->getEntityManager(); | |
$postData = $request->get('form'); | |
$newUser = true; | |
if($postData['id'] === '') { | |
$user = new \Ingenii\HomeBudgetBundle\Entity\User(); | |
} else { | |
$user = $em->find('IngeniiHomeBudgetBundle:User', $postData['id']); | |
$newUser = false; | |
} | |
$form = $this->getUserForm($user); | |
if ($request->getMethod() == 'POST') { | |
$form->bindRequest($request); | |
if($form->isValid()) { | |
$user = $form->getData(); | |
if($newUser) { | |
$em->persist($user); | |
} | |
$em->flush(); | |
} | |
} | |
return $this->redirect($this->generateUrl('homebudget_dashboard_useroverview')); | |
} | |
protected function getUserForm($user) { | |
return $this->get('form.factory')->createBuilder('form', $user) | |
->add('name', 'text') | |
->add('password','password') | |
->add('id','hidden') | |
->getForm(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment