Skip to content

Instantly share code, notes, and snippets.

@metalvarez
Created November 15, 2013 13:30
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 metalvarez/7484345 to your computer and use it in GitHub Desktop.
Save metalvarez/7484345 to your computer and use it in GitHub Desktop.
<?php
/**
* @file Acme\CommonsBundle\Controller\CrudController.php
* @package AcmeCommonsBundle
*/
namespace Acme\CommonsBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Acme\CommonsBundle\Model\Controller\InitializableControllerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
* Parent CRUD class
*
* @author "Víctor Hugo Álvarez Pérez <metalvarez@gmail.com>"
* @package AcmeCommonsBundle
* @created 24/10/2013
* @version 0.1
*/
class CrudController extends Controller implements InitializableControllerInterface {
protected $filterParams = array();
protected $entityClassName;
protected $formClassName;
protected $repositoryName;
protected $templateFolder;
protected $reflectionGuesser;
/* (non-PHPdoc)
* @see \Siefa\CommonsBundle\Model\Controller\InitializableControllerInterface::initialize()
*/
public function initialize() {
/**
*
*pasamos el controlador al servicio para determinar el nombre de la entidad usando reflection
**/
$this->reflectionGuesser = $this->get('entity_reflection_guesser')->inizialize($this);
$this->entityClassName = $this->reflectionGuesser->guessEntityName(); //obtenemos el nombre de la entidad
$this->repositoryName = $this->reflectionGuesser->guessEntityBundleShortName(); //obtenemos el nombre del repositorio
$this->templateFolder = $this->reflectionGuesser->guessEntityBundleShortName(); //obtenemos el nombre de la carpeta de las plantillas
$this->formClassName = $this->reflectionGuesser->guessFormTypeName(); //obtenemos el nombre del formulario
}
protected function getFormType() {
return new $this->formClassName();
}
protected function applyFilter() {
}
/**
* Algunas funciones útiles, en algunos casos los callbacks de Doctrine no son suficientes.
*/
protected function preInsert($form, $entity) {
}
protected function postInsert($form, $entity) {
}
protected function preValidate($form, $entity) {
}
protected function postValidate($form, $entity) {
}
protected function preUpdate($form, $entity) {
}
protected function postUpdate($form, $entity) {
}
protected function preDelete($form, $entity) {
}
protected function postDelete($form, $entity) {
}
/**
* Lists all entities.
*
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$qb = $em->getRepository($this->repositoryName)->createQueryBuilder('q')->select('q');
$query = $qb->getQuery();
$paginator = $this->get('knp_paginator');
$entities = $paginator->paginate(
$query, $this->get('request')->query->get('page', 1), 15
);
return $this->render($this->templateFolder.':index.html.twig', array(
'sort_field' => $this->getRequest()->get('sort'),
'order_direction' => $this->getRequest()->get('direction'),
'entities' => $entities
));
}
/**
* Displays a form to create a new entity.
*
*/
public function newAction()
{
$entity = new $this->entityClassName();
$form = $this->createForm($this->getFormType(), $entity);
return $this->render($this->templateFolder.':new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
/**
* Creates a new entity.
*
*/
public function createAction (Request $request) {
$entity = new $this->entityClassName();
$form = $this->createForm($this->getFormType(), $entity);
$form->submit($request);
$this->preValidate($form, $entity);
if ($form->isValid()) {
$this->postValidate($form, $entity);
$em = $this->getDoctrine()->getManager();
$this->preInsert($form, $entity);
$em->persist($entity);
$em->flush();
$this->postInsert($form, $entity);
$message = $this->get('translator')->trans('item.created');
$this->get('session')->getFlashBag()->add('success', $message);
$lower_case_entity_short_name = strtolower($this->reflectionGuesser->guessEntityShortName());
$show_action_route = $lower_case_entity_short_name."_show";
return $this->redirect($this->generateUrl($show_action_route, array ('id' => $entity->getId())));
}
$message = $this->get('translator')->trans('form.error');
$this->get('session')->getFlashBag()->add('error', $message);
return $this->render($this->templateFolder.':new.html.twig', array (
'entity' => $entity,
'form' => $form->createView()
));
}
/**
* Finds and displays an entity.
*
*/
public function showAction ($id) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository($this->repositoryName)->find($id);
if (!$entity) {
throw $this->createNotFoundException(sprintf('Unable to find %s entity.', $this->reflectionGuesser->guessEntityShortName()));
};
$deleteForm = $this->createDeleteForm($id);
return $this->render($this->templateFolder.':show.html.twig', array (
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
'id' => $id
));
}
/**
* Displays a form to edit an existing entity.
*
*/
public function editAction ($id) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository($this->repositoryName)->find($id);
if (!$entity) {
throw $this->createNotFoundException(sprintf('Unable to find %s entity.', $this->reflectionGuesser->guessEntityShortName()));
}
$editForm = $this->createForm($this->getFormType(), $entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render($this->templateFolder.':edit.html.twig', array (
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView()
));
}
/**
* Edits an existing entity.
*
*/
public function updateAction (Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository($this->repositoryName)->find($id);
if (!$entity) {
throw $this->createNotFoundException(sprintf('Unable to find %s entity.', $this->reflectionGuesser->guessEntityShortName()));
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createForm($this->getFormType(), $entity);
$editForm->submit($request);
$this->preValidate($editForm, $entity);
if ($editForm->isValid()) {
$this->postValidate($editForm, $entity);
$this->preUpdate($editForm, $entity);
$em->persist($entity);
$em->flush();
$this->postUpdate($editForm, $entity);
$message = $this->get('translator')->trans('item.edited');
$this->get('session')->getFlashBag()->add('success', $message);
$lower_case_entity_short_name = strtolower($this->reflectionGuesser->guessEntityShortName());
$edit_action_route = $lower_case_entity_short_name."_edit";
return $this->redirect($this->generateUrl($edit_action_route, array ('id' => $id)));
}
$message = $this->get('translator')->trans('form.error');
$this->get('session')->getFlashBag()->add('error', $message);
return $this->render($this->templateFolder.':edit.html.twig', array (
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView()
));
}
/**
* Deletes an entity.
*
*/
public function deleteAction (Request $request, $id) {
$form = $this->createDeleteForm($id);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository($this->repositoryName)->find($id);
if (!$entity) {
throw $this->createNotFoundExcetion(sprintf('Unable to find %s entity.', $this->reflectionGuesser->guessEntityShortName()));
}
$this->preDelete($form, $entity);
$em->remove($entity);
$em->flush();
$this->postDelete($form, $entity);
}
$message = $this->get('translator')->trans('item.deleted');
$this->get('session')->getFlashBag()->add('success', $message);
$lower_case_entity_short_name = strtolower($this->reflectionGuesser->guessEntityShortName());
$index_action_route = $lower_case_entity_short_name."_index";
return $this->redirect($this->generateUrl($index_action_route));
}
/**
* Creates a form to delete a Item entity by id.
*
* @param mixed $id The entity id
*
* @return Symfony\Component\Form\Form The form
*/
protected function createDeleteForm($id)
{
return $this->createFormBuilder(array('id' => $id))
->add('id', 'hidden')
->getForm()
;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment