/
AdminController.php
789 lines (671 loc) · 28.8 KB
/
AdminController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
<?php
namespace EasyCorp\Bundle\EasyAdminBundle\Controller;
use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\QueryBuilder;
use EasyCorp\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
use EasyCorp\Bundle\EasyAdminBundle\Exception\EntityRemoveException;
use EasyCorp\Bundle\EasyAdminBundle\Exception\ForbiddenActionException;
use EasyCorp\Bundle\EasyAdminBundle\Exception\NoEntitiesConfiguredException;
use EasyCorp\Bundle\EasyAdminBundle\Exception\UndefinedEntityException;
use EasyCorp\Bundle\EasyAdminBundle\Form\Util\FormTypeHelper;
use Pagerfanta\Pagerfanta;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\Routing\Annotation\Route;
/**
* The controller used to render all the default EasyAdmin actions.
*
* @author Javier Eguiluz <javier.eguiluz@gmail.com>
*/
class AdminController extends Controller
{
/** @var array The full configuration of the entire backend */
protected $config;
/** @var array The full configuration of the current entity */
protected $entity = [];
/** @var Request The instance of the current Symfony request */
protected $request;
/** @var EntityManager The Doctrine entity manager for the current entity */
protected $em;
/**
* @Route("/", name="easyadmin")
*
* @param Request $request
*
* @return RedirectResponse|Response
*
* @throws ForbiddenActionException
*/
public function indexAction(Request $request)
{
$this->initialize($request);
if (null === $request->query->get('entity')) {
return $this->redirectToBackendHomepage();
}
$action = $request->query->get('action', 'list');
if (!$this->isActionAllowed($action)) {
throw new ForbiddenActionException(['action' => $action, 'entity_name' => $this->entity['name']]);
}
return $this->executeDynamicMethod($action.'<EntityName>Action');
}
/**
* Utility method which initializes the configuration of the entity on which
* the user is performing the action.
*
* @param Request $request
*
* @throws NoEntitiesConfiguredException
* @throws UndefinedEntityException
*/
protected function initialize(Request $request)
{
$this->dispatch(EasyAdminEvents::PRE_INITIALIZE);
$this->config = $this->get('easyadmin.config.manager')->getBackendConfig();
if (0 === \count($this->config['entities'])) {
throw new NoEntitiesConfiguredException();
}
// this condition happens when accessing the backend homepage and before
// redirecting to the default page set as the homepage
if (null === $entityName = $request->query->get('entity')) {
return;
}
if (!array_key_exists($entityName, $this->config['entities'])) {
throw new UndefinedEntityException(['entity_name' => $entityName]);
}
$this->entity = $this->get('easyadmin.config.manager')->getEntityConfig($entityName);
$action = $request->query->get('action', 'list');
if (!$request->query->has('sortField')) {
$sortField = $this->entity[$action]['sort']['field'] ?? $this->entity['primary_key_field_name'];
$request->query->set('sortField', $sortField);
}
if (!$request->query->has('sortDirection')) {
$sortDirection = $this->entity[$action]['sort']['direction'] ?? 'DESC';
$request->query->set('sortDirection', $sortDirection);
}
$this->em = $this->getDoctrine()->getManagerForClass($this->entity['class']);
$this->request = $request;
$this->dispatch(EasyAdminEvents::POST_INITIALIZE);
}
protected function dispatch($eventName, array $arguments = [])
{
$arguments = array_replace([
'config' => $this->config,
'em' => $this->em,
'entity' => $this->entity,
'request' => $this->request,
], $arguments);
$subject = $arguments['paginator'] ?? $arguments['entity'];
$event = new GenericEvent($subject, $arguments);
$this->get('event_dispatcher')->dispatch($eventName, $event);
}
/**
* The method that returns the values displayed by an autocomplete field
* based on the user's input.
*
* @return JsonResponse
*/
protected function autocompleteAction()
{
$results = $this->get('easyadmin.autocomplete')->find(
$this->request->query->get('entity'),
$this->request->query->get('query'),
$this->request->query->get('page', 1)
);
return new JsonResponse($results);
}
/**
* The method that is executed when the user performs a 'list' action on an entity.
*
* @return Response
*/
protected function listAction()
{
$this->dispatch(EasyAdminEvents::PRE_LIST);
$fields = $this->entity['list']['fields'];
$paginator = $this->findAll($this->entity['class'], $this->request->query->get('page', 1), $this->entity['list']['max_results'], $this->request->query->get('sortField'), $this->request->query->get('sortDirection'), $this->entity['list']['dql_filter']);
$this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
$parameters = [
'paginator' => $paginator,
'fields' => $fields,
'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
];
return $this->executeDynamicMethod('render<EntityName>Template', ['list', $this->entity['templates']['list'], $parameters]);
}
/**
* The method that is executed when the user performs a 'edit' action on an entity.
*
* @return Response|RedirectResponse
*
* @throws \RuntimeException
*/
protected function editAction()
{
$this->dispatch(EasyAdminEvents::PRE_EDIT);
$id = $this->request->query->get('id');
$easyadmin = $this->request->attributes->get('easyadmin');
$entity = $easyadmin['item'];
if ($this->request->isXmlHttpRequest() && $property = $this->request->query->get('property')) {
$newValue = 'true' === mb_strtolower($this->request->query->get('newValue'));
$fieldsMetadata = $this->entity['list']['fields'];
if (!isset($fieldsMetadata[$property]) || 'toggle' !== $fieldsMetadata[$property]['dataType']) {
throw new \RuntimeException(sprintf('The type of the "%s" property is not "toggle".', $property));
}
$this->updateEntityProperty($entity, $property, $newValue);
// cast to integer instead of string to avoid sending empty responses for 'false'
return new Response((int) $newValue);
}
$fields = $this->entity['edit']['fields'];
$editForm = $this->executeDynamicMethod('create<EntityName>EditForm', [$entity, $fields]);
$deleteForm = $this->createDeleteForm($this->entity['name'], $id);
$editForm->handleRequest($this->request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
$this->executeDynamicMethod('update<EntityName>Entity', [$entity, $editForm]);
$this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
return $this->redirectToReferrer();
}
$this->dispatch(EasyAdminEvents::POST_EDIT);
$parameters = [
'form' => $editForm->createView(),
'entity_fields' => $fields,
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
];
return $this->executeDynamicMethod('render<EntityName>Template', ['edit', $this->entity['templates']['edit'], $parameters]);
}
/**
* The method that is executed when the user performs a 'show' action on an entity.
*
* @return Response
*/
protected function showAction()
{
$this->dispatch(EasyAdminEvents::PRE_SHOW);
$id = $this->request->query->get('id');
$easyadmin = $this->request->attributes->get('easyadmin');
$entity = $easyadmin['item'];
$fields = $this->entity['show']['fields'];
$deleteForm = $this->createDeleteForm($this->entity['name'], $id);
$this->dispatch(EasyAdminEvents::POST_SHOW, [
'deleteForm' => $deleteForm,
'fields' => $fields,
'entity' => $entity,
]);
$parameters = [
'entity' => $entity,
'fields' => $fields,
'delete_form' => $deleteForm->createView(),
];
return $this->executeDynamicMethod('render<EntityName>Template', ['show', $this->entity['templates']['show'], $parameters]);
}
/**
* The method that is executed when the user performs a 'new' action on an entity.
*
* @return Response|RedirectResponse
*/
protected function newAction()
{
$this->dispatch(EasyAdminEvents::PRE_NEW);
$entity = $this->executeDynamicMethod('createNew<EntityName>Entity');
$easyadmin = $this->request->attributes->get('easyadmin');
$easyadmin['item'] = $entity;
$this->request->attributes->set('easyadmin', $easyadmin);
$fields = $this->entity['new']['fields'];
$newForm = $this->executeDynamicMethod('create<EntityName>NewForm', [$entity, $fields]);
$newForm->handleRequest($this->request);
if ($newForm->isSubmitted() && $newForm->isValid()) {
$this->dispatch(EasyAdminEvents::PRE_PERSIST, ['entity' => $entity]);
$this->executeDynamicMethod('persist<EntityName>Entity', [$entity, $newForm]);
$this->dispatch(EasyAdminEvents::POST_PERSIST, ['entity' => $entity]);
return $this->redirectToReferrer();
}
$this->dispatch(EasyAdminEvents::POST_NEW, [
'entity_fields' => $fields,
'form' => $newForm,
'entity' => $entity,
]);
$parameters = [
'form' => $newForm->createView(),
'entity_fields' => $fields,
'entity' => $entity,
];
return $this->executeDynamicMethod('render<EntityName>Template', ['new', $this->entity['templates']['new'], $parameters]);
}
/**
* The method that is executed when the user performs a 'delete' action to
* remove any entity.
*
* @return RedirectResponse
*
* @throws EntityRemoveException
*/
protected function deleteAction()
{
$this->dispatch(EasyAdminEvents::PRE_DELETE);
if ('DELETE' !== $this->request->getMethod()) {
return $this->redirect($this->generateUrl('easyadmin', ['action' => 'list', 'entity' => $this->entity['name']]));
}
$id = $this->request->query->get('id');
$form = $this->createDeleteForm($this->entity['name'], $id);
$form->handleRequest($this->request);
if ($form->isSubmitted() && $form->isValid()) {
$easyadmin = $this->request->attributes->get('easyadmin');
$entity = $easyadmin['item'];
$this->dispatch(EasyAdminEvents::PRE_REMOVE, ['entity' => $entity]);
try {
$this->executeDynamicMethod('remove<EntityName>Entity', [$entity, $form]);
} catch (ForeignKeyConstraintViolationException $e) {
throw new EntityRemoveException(['entity_name' => $this->entity['name'], 'message' => $e->getMessage()]);
}
$this->dispatch(EasyAdminEvents::POST_REMOVE, ['entity' => $entity]);
}
$this->dispatch(EasyAdminEvents::POST_DELETE);
return $this->redirectToReferrer();
}
/**
* The method that is executed when the user performs a query on an entity.
*
* @return Response
*/
protected function searchAction()
{
$this->dispatch(EasyAdminEvents::PRE_SEARCH);
$query = trim($this->request->query->get('query'));
// if the search query is empty, redirect to the 'list' action
if ('' === $query) {
$queryParameters = array_filter(array_replace($this->request->query->all(), ['action' => 'list', 'query' => null]));
return $this->redirect($this->get('router')->generate('easyadmin', $queryParameters));
}
$searchableFields = $this->entity['search']['fields'];
$defaultSortField = isset($this->entity['search']['sort']['field']) ? $this->entity['search']['sort']['field'] : null;
$defaultSortDirection = isset($this->entity['search']['sort']['direction']) ? $this->entity['search']['sort']['direction'] : null;
$paginator = $this->findBy(
$this->entity['class'],
$query,
$searchableFields,
$this->request->query->get('page', 1),
$this->entity['list']['max_results'],
$this->request->query->get('sortField', $defaultSortField),
$this->request->query->get('sortDirection', $defaultSortDirection),
$this->entity['search']['dql_filter']
);
$fields = $this->entity['list']['fields'];
$this->dispatch(EasyAdminEvents::POST_SEARCH, [
'fields' => $fields,
'paginator' => $paginator,
]);
$parameters = [
'paginator' => $paginator,
'fields' => $fields,
'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
];
return $this->executeDynamicMethod('render<EntityName>Template', ['search', $this->entity['templates']['list'], $parameters]);
}
/**
* It updates the value of some property of some entity to the new given value.
*
* @param mixed $entity The instance of the entity to modify
* @param string $property The name of the property to change
* @param bool $value The new value of the property
*
* @throws \RuntimeException
*/
protected function updateEntityProperty($entity, $property, $value)
{
$entityConfig = $this->entity;
if (!$this->get('easy_admin.property_accessor')->isWritable($entity, $property)) {
throw new \RuntimeException(sprintf('The "%s" property of the "%s" entity is not writable.', $property, $entityConfig['name']));
}
$this->get('easy_admin.property_accessor')->setValue($entity, $property, $value);
$this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity, 'newValue' => $value]);
$this->executeDynamicMethod('update<EntityName>Entity', [$entity]);
$this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity, 'newValue' => $value]);
$this->dispatch(EasyAdminEvents::POST_EDIT);
}
/**
* Creates a new object of the current managed entity.
* This method is mostly here for override convenience, because it allows
* the user to use his own method to customize the entity instantiation.
*
* @return object
*/
protected function createNewEntity()
{
$entityFullyQualifiedClassName = $this->entity['class'];
return new $entityFullyQualifiedClassName();
}
/**
* Allows applications to modify the entity associated with the item being
* created while persisting it.
*
* @param object $entity
*/
protected function persistEntity($entity)
{
$this->em->persist($entity);
$this->em->flush();
}
/**
* Allows applications to modify the entity associated with the item being
* edited before updating it.
*
* @param object $entity
*/
protected function updateEntity($entity)
{
$this->em->persist($entity);
$this->em->flush();
}
/**
* Allows applications to modify the entity associated with the item being
* deleted before removing it.
*
* @param object $entity
*/
protected function removeEntity($entity)
{
$this->em->remove($entity);
$this->em->flush();
}
/**
* Performs a database query to get all the records related to the given
* entity. It supports pagination and field sorting.
*
* @param string $entityClass
* @param int $page
* @param int $maxPerPage
* @param string|null $sortField
* @param string|null $sortDirection
* @param string|null $dqlFilter
*
* @return Pagerfanta The paginated query results
*/
protected function findAll($entityClass, $page = 1, $maxPerPage = 15, $sortField = null, $sortDirection = null, $dqlFilter = null)
{
if (!\in_array(strtoupper($sortDirection), ['ASC', 'DESC'])) {
$sortDirection = 'DESC';
}
$queryBuilder = $this->executeDynamicMethod('create<EntityName>ListQueryBuilder', [$entityClass, $sortDirection, $sortField, $dqlFilter]);
$this->dispatch(EasyAdminEvents::POST_LIST_QUERY_BUILDER, [
'query_builder' => $queryBuilder,
'sort_field' => $sortField,
'sort_direction' => $sortDirection,
]);
return $this->get('easyadmin.paginator')->createOrmPaginator($queryBuilder, $page, $maxPerPage);
}
/**
* Creates Query Builder instance for all the records.
*
* @param string $entityClass
* @param string $sortDirection
* @param string|null $sortField
* @param string|null $dqlFilter
*
* @return QueryBuilder The Query Builder instance
*/
protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
{
return $this->get('easyadmin.query_builder')->createListQueryBuilder($this->entity, $sortField, $sortDirection, $dqlFilter);
}
/**
* Performs a database query based on the search query provided by the user.
* It supports pagination and field sorting.
*
* @param string $entityClass
* @param string $searchQuery
* @param array $searchableFields
* @param int $page
* @param int $maxPerPage
* @param string|null $sortField
* @param string|null $sortDirection
* @param string|null $dqlFilter
*
* @return Pagerfanta The paginated query results
*/
protected function findBy($entityClass, $searchQuery, array $searchableFields, $page = 1, $maxPerPage = 15, $sortField = null, $sortDirection = null, $dqlFilter = null)
{
if (empty($sortDirection) || !in_array(strtoupper($sortDirection), ['ASC', 'DESC'])) {
$sortDirection = 'DESC';
}
$queryBuilder = $this->executeDynamicMethod('create<EntityName>SearchQueryBuilder', [$entityClass, $searchQuery, $searchableFields, $sortField, $sortDirection, $dqlFilter]);
$this->dispatch(EasyAdminEvents::POST_SEARCH_QUERY_BUILDER, [
'query_builder' => $queryBuilder,
'search_query' => $searchQuery,
'searchable_fields' => $searchableFields,
]);
return $this->get('easyadmin.paginator')->createOrmPaginator($queryBuilder, $page, $maxPerPage);
}
/**
* Creates Query Builder instance for search query.
*
* @param string $entityClass
* @param string $searchQuery
* @param array $searchableFields
* @param string|null $sortField
* @param string|null $sortDirection
* @param string|null $dqlFilter
*
* @return QueryBuilder The Query Builder instance
*/
protected function createSearchQueryBuilder($entityClass, $searchQuery, array $searchableFields, $sortField = null, $sortDirection = null, $dqlFilter = null)
{
return $this->get('easyadmin.query_builder')->createSearchQueryBuilder($this->entity, $searchQuery, $sortField, $sortDirection, $dqlFilter);
}
/**
* Creates the form used to edit an entity.
*
* @param object $entity
* @param array $entityProperties
*
* @return Form|FormInterface
*/
protected function createEditForm($entity, array $entityProperties)
{
return $this->createEntityForm($entity, $entityProperties, 'edit');
}
/**
* Creates the form used to create an entity.
*
* @param object $entity
* @param array $entityProperties
*
* @return Form|FormInterface
*/
protected function createNewForm($entity, array $entityProperties)
{
return $this->createEntityForm($entity, $entityProperties, 'new');
}
/**
* Creates the form builder of the form used to create or edit the given entity.
*
* @param object $entity
* @param string $view The name of the view where this form is used ('new' or 'edit')
*
* @return FormBuilder
*/
protected function createEntityFormBuilder($entity, $view)
{
$formOptions = $this->executeDynamicMethod('get<EntityName>EntityFormOptions', [$entity, $view]);
return $this->get('form.factory')->createNamedBuilder(mb_strtolower($this->entity['name']), FormTypeHelper::getTypeClass('easyadmin'), $entity, $formOptions);
}
/**
* Retrieves the list of form options before sending them to the form builder.
* This allows adding dynamic logic to the default form options.
*
* @param object $entity
* @param string $view
*
* @return array
*/
protected function getEntityFormOptions($entity, $view)
{
$formOptions = $this->entity[$view]['form_options'];
$formOptions['entity'] = $this->entity['name'];
$formOptions['view'] = $view;
return $formOptions;
}
/**
* Creates the form object used to create or edit the given entity.
*
* @param object $entity
* @param array $entityProperties
* @param string $view
*
* @return FormInterface
*
* @throws \Exception
*/
protected function createEntityForm($entity, array $entityProperties, $view)
{
if (method_exists($this, $customMethodName = 'create'.$this->entity['name'].'EntityForm')) {
$form = $this->{$customMethodName}($entity, $entityProperties, $view);
if (!$form instanceof FormInterface) {
throw new \UnexpectedValueException(sprintf(
'The "%s" method must return a FormInterface, "%s" given.',
$customMethodName, \is_object($form) ? \get_class($form) : \gettype($form)
));
}
return $form;
}
$formBuilder = $this->executeDynamicMethod('create<EntityName>EntityFormBuilder', [$entity, $view]);
if (!$formBuilder instanceof FormBuilderInterface) {
throw new \UnexpectedValueException(sprintf(
'The "%s" method must return a FormBuilderInterface, "%s" given.',
'createEntityForm', \is_object($formBuilder) ? \get_class($formBuilder) : \gettype($formBuilder)
));
}
return $formBuilder->getForm();
}
/**
* Creates the form used to delete an entity. It must be a form because
* the deletion of the entity are always performed with the 'DELETE' HTTP method,
* which requires a form to work in the current browsers.
*
* @param string $entityName
* @param int|string $entityId When reusing the delete form for multiple entities, a pattern string is passed instead of an integer
*
* @return Form|FormInterface
*/
protected function createDeleteForm($entityName, $entityId)
{
/** @var FormBuilder $formBuilder */
$formBuilder = $this->get('form.factory')->createNamedBuilder('delete_form')
->setAction($this->generateUrl('easyadmin', ['action' => 'delete', 'entity' => $entityName, 'id' => $entityId]))
->setMethod('DELETE')
;
$formBuilder->add('submit', FormTypeHelper::getTypeClass('submit'), ['label' => 'delete_modal.action', 'translation_domain' => 'EasyAdminBundle']);
// needed to avoid submitting empty delete forms (see issue #1409)
$formBuilder->add('_easyadmin_delete_flag', FormTypeHelper::getTypeClass('hidden'), ['data' => '1']);
return $formBuilder->getForm();
}
/**
* Utility method that checks if the given action is allowed for
* the current entity.
*
* @param string $actionName
*
* @return bool
*/
protected function isActionAllowed($actionName)
{
return false === \in_array($actionName, $this->entity['disabled_actions'], true);
}
/**
* Given a method name pattern, it looks for the customized version of that
* method (based on the entity name) and executes it. If the custom method
* does not exist, it executes the regular method.
*
* For example:
* executeDynamicMethod('create<EntityName>Entity') and the entity name is 'User'
* if 'createUserEntity()' exists, execute it; otherwise execute 'createEntity()'
*
* @param string $methodNamePattern The pattern of the method name (dynamic parts are enclosed with <> angle brackets)
* @param array $arguments The arguments passed to the executed method
*
* @return mixed
*/
protected function executeDynamicMethod($methodNamePattern, array $arguments = [])
{
$methodName = str_replace('<EntityName>', $this->entity['name'], $methodNamePattern);
if (!\is_callable([$this, $methodName])) {
$methodName = str_replace('<EntityName>', '', $methodNamePattern);
}
return \call_user_func_array([$this, $methodName], $arguments);
}
/**
* Generates the backend homepage and redirects to it.
*/
protected function redirectToBackendHomepage()
{
$homepageConfig = $this->config['homepage'];
$url = $homepageConfig['url'] ?? $this->get('router')->generate($homepageConfig['route'], $homepageConfig['params']);
return $this->redirect($url);
}
/**
* @return RedirectResponse
*/
protected function redirectToReferrer()
{
$refererUrl = $this->request->query->get('referer', '');
$refererAction = $this->request->query->get('action');
// 1. redirect to list if possible
if ($this->isActionAllowed('list')) {
if (!empty($refererUrl)) {
return $this->redirect(urldecode($refererUrl));
}
return $this->redirectToRoute('easyadmin', [
'action' => 'list',
'entity' => $this->entity['name'],
'menuIndex' => $this->request->query->get('menuIndex'),
'submenuIndex' => $this->request->query->get('submenuIndex'),
]);
}
// 2. from new|edit action, redirect to edit if possible
if (\in_array($refererAction, ['new', 'edit']) && $this->isActionAllowed('edit')) {
return $this->redirectToRoute('easyadmin', [
'action' => 'edit',
'entity' => $this->entity['name'],
'menuIndex' => $this->request->query->get('menuIndex'),
'submenuIndex' => $this->request->query->get('submenuIndex'),
'id' => ('new' === $refererAction)
? PropertyAccess::createPropertyAccessor()->getValue($this->request->attributes->get('easyadmin')['item'], $this->entity['primary_key_field_name'])
: $this->request->query->get('id'),
]);
}
// 3. from new action, redirect to new if possible
if ('new' === $refererAction && $this->isActionAllowed('new')) {
return $this->redirectToRoute('easyadmin', [
'action' => 'new',
'entity' => $this->entity['name'],
'menuIndex' => $this->request->query->get('menuIndex'),
'submenuIndex' => $this->request->query->get('submenuIndex'),
]);
}
return $this->redirectToBackendHomepage();
}
/**
* Used to add/modify/remove parameters before passing them to the Twig template.
* Instead of defining a render method per action (list, show, search, etc.) use
* the $actionName argument to discriminate between actions.
*
* @param string $actionName The name of the current action (list, show, new, etc.)
* @param string $templatePath The path of the Twig template to render
* @param array $parameters The parameters passed to the template
*
* @return Response
*/
protected function renderTemplate($actionName, $templatePath, array $parameters = [])
{
return $this->render($templatePath, $parameters);
}
}