Skip to content

Instantly share code, notes, and snippets.

@coreymcmahon
Created May 7, 2012 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coreymcmahon/2627724 to your computer and use it in GitHub Desktop.
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
<?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