CRUD: improve index view

This commit is contained in:
2020-06-11 15:58:31 +02:00
parent 278d7f5772
commit 937792fa2d
3 changed files with 70 additions and 11 deletions

View File

@@ -27,14 +27,26 @@ use Chill\PersonBundle\Entity\Person;
*/
class EntityPersonCRUDController extends CRUDController
{
protected function createEntity($action, Request $request): object
/**
* Extract the person from the request
*
* the person parameter will be `person_id` and must be
* present in the query
*
* If the parameter is not set, this method will return null.
*
* If the person id does not exists, the method will throw a
* Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*
* @param Request $request
* @throws Symfony\Component\HttpKernel\Exception\NotFoundHttpException if the person with given id is not found
*/
protected function getPerson(Request $request): ?Person
{
if (FALSE === $request->query->has('person_id')) {
throw $this->createNotFoundException('the person is not set');
return null;
}
$entity = parent::createEntity($action, $request);
$person = $this->getDoctrine()
->getRepository(Person::class)
->find($request->query->getInt('person_id'))
@@ -44,11 +56,38 @@ class EntityPersonCRUDController extends CRUDController
throw $this->createNotFoundException('the person with this id is not found');
}
return $person;
}
protected function createEntity($action, Request $request): object
{
$entity = parent::createEntity($action, $request);
$person = $this->getPerson($request);
$entity->setPerson($person);
return $entity;
}
protected function generateTemplateParameter(string $action, $entity, Request $request, array $defaultTemplateParameters = array()): array
{
$person = $this->getPerson($request);
if (NULL === $person) {
throw new \Exception("the `person_id` parameter is not set in the query. "
. "You should set it or override the current method to allow another "
. "behaviour: ".__METHOD__);
}
return parent::generateTemplateParameter(
$action,
$entity,
$request,
\array_merge([ 'person' => $person ], $defaultTemplateParameters)
);
}
protected function getTemplateFor($action, $entity, Request $request)
{
if ($this->hasCustomTemplate($action, $entity, $request)) {
@@ -64,6 +103,8 @@ class EntityPersonCRUDController extends CRUDController
return '@ChillPerson/CRUD/view.html.twig';
case 'delete':
return '@ChillPerson/CRUD/delete.html.twig';
case 'index':
return '@ChillPerson/CRUD/index.html.twig';
default:
return parent::getTemplateFor($action, $entity, $request);
}
@@ -76,7 +117,7 @@ class EntityPersonCRUDController extends CRUDController
switch ($next) {
case "save-and-close":
return $this->redirectToRoute('chill_crud_'.$this->getCrudName().'_index', [
'id' => $entity->getPerson()->getId()
'person_id' => $entity->getPerson()->getId()
]);
case "save-and-new":
return $this->redirectToRoute('chill_crud_'.$this->getCrudName().'_new', [
@@ -88,4 +129,6 @@ class EntityPersonCRUDController extends CRUDController
]);
}
}
}