Created
May 7, 2012 13:22
-
-
Save coreymcmahon/2627724 to your computer and use it in GitHub Desktop.
A controller used to add and view a user list - http://www.symfonycentral.com/symfony-does-validation.html
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 MyCompany\BlogBundle\Controller; | |
use Symfony\Bundle\FrameworkBundle\Controller\Controller; | |
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; | |
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; | |
use Doctrine\ORM\EntityRepository; | |
/* Import the entity and form classes */ | |
use MyCompany\BlogBundle\Entity\User; | |
use MyCompany\BlogBundle\Form\UserType; | |
class UserController extends Controller | |
{ | |
/** | |
* @Route("/users/", name="user_index") | |
* @Template() | |
*/ | |
public function indexAction() | |
{ | |
$users = $this->getDoctrine() | |
->getRepository('MyCompanyBlogBundle:User') | |
->findAll(); | |
return array( 'users' => $users ); | |
} | |
/** | |
* @Route("/users/new", name="user_create") | |
* @Template() | |
*/ | |
public function createAction() | |
{ | |
$user = new User(); | |
/* Create the form instance using the form and entity classes */ | |
$form = $this->createForm(new UserType(), $user); | |
if ($this->getRequest()->getMethod() == "POST") { | |
/* On postback, bind the form values to the form object */ | |
$form->bind($this->getRequest()->get($form->getName())); | |
if ($form->isValid()) { | |
/* If the assertions pass, we can persist the object... */ | |
$em = $this->getDoctrine()->getEntityManager(); | |
$em->persist($user); | |
$em->flush(); | |
/* ... and redirect */ | |
$this->redirect( | |
$this->generateUrl('user_index') | |
); | |
} | |
} | |
/* Otherwise show the form again. Any errors that were | |
* triggered by isValid() will be displayed | |
*/ | |
return array('form' => $form->createView()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment