CRUDController.php 8.98 KB
Newer Older
Julien Jorry committed
1 2 3 4 5 6
<?php

namespace App\Controller\CRUD;

use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
7 8
use Symfony\Component\Form\FormRenderer;
use Symfony\Component\Form\FormView;
Julien Jorry committed
9 10 11 12
use Symfony\Component\HttpFoundation\RedirectResponse;

class CRUDController extends Controller
{
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
    /**
     * Create action.
     *
     * @throws AccessDeniedException If access is not granted
     *
     * @return Response
     */
    public function createAction()
    {
        $request = $this->getRequest();
        // the key used to lookup the template
        $templateKey = 'edit';

        $this->admin->checkAccess('create');

        $class = new \ReflectionClass($this->admin->hasActiveSubClass() ? $this->admin->getActiveSubClass() : $this->admin->getClass());

        if ($class->isAbstract()) {
            return $this->renderWithExtraParams(
                '@SonataAdmin/CRUD/select_subclass.html.twig',
                [
                    'base_template' => $this->getBaseTemplate(),
                    'admin' => $this->admin,
                    'action' => 'create',
                ],
                null
            );
        }

        $newObject = $this->admin->getNewInstance();

        $preResponse = $this->preCreate($request, $newObject);
        if (null !== $preResponse) {
            return $preResponse;
        }

        $this->admin->setSubject($newObject);

        $form = $this->admin->getForm();

        $form->setData($newObject);
        $form->handleRequest($request);

        if ($form->isSubmitted()) {
            $isFormValid = $form->isValid();

            // persist if the form was valid and if in preview mode the preview was approved
            if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
                /** @phpstan-var T $submittedObject */
                $submittedObject = $form->getData();
                $this->admin->setSubject($submittedObject);
                $this->admin->checkAccess('create', $submittedObject);

                try {
                    $newObject = $this->admin->create($submittedObject);

                    if ($this->isXmlHttpRequest()) {
                        return $this->handleXmlHttpRequestSuccessResponse($request, $newObject);
                    }
                    // ADD FOR KOHINOS => test if object newly created is null to send flash message success !
                    if (null != $newObject) {
                        $this->addFlash(
                            'sonata_flash_success',
                            $this->trans(
                                'flash_create_success',
                                ['%name%' => $this->escapeHtml($this->admin->toString($newObject))],
                                'SonataAdminBundle'
                            )
                        );
                    }

                    // redirect to edit mode
                    return $this->redirectTo($newObject);
                } catch (ModelManagerException $e) {
                    $this->handleModelManagerException($e);

                    $isFormValid = false;
                }
            }

            // show an error message if the form failed validation
            if (!$isFormValid) {
                if ($this->isXmlHttpRequest() && null !== ($response = $this->handleXmlHttpRequestErrorResponse($request, $form))) {
                    return $response;
                }

                $this->addFlash(
                    'sonata_flash_error',
                    $this->trans(
                        'flash_create_error',
                        ['%name%' => $this->escapeHtml($this->admin->toString($newObject))],
                        'SonataAdminBundle'
                    )
                );
            } elseif ($this->isPreviewRequested()) {
                // pick the preview template if the form was valid and preview was requested
                $templateKey = 'preview';
                $this->admin->getShow();
            }
        }

        $formView = $form->createView();
        // set the theme for the current Admin Form
        $this->setFormTheme($formView, $this->admin->getFormTheme());

        // NEXT_MAJOR: Remove this line and use commented line below it instead
        $template = $this->admin->getTemplate($templateKey);
        // $template = $this->templateRegistry->getTemplate($templateKey);

        return $this->renderWithExtraParams($template, [
            'action' => 'create',
            'form' => $formView,
            'object' => $newObject,
            'objectId' => null,
        ], null);
    }
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
    // /**
    //  * @inheritdoc
    //  */
    // public function exportAction(Request $request)
    // {
    //     $this->admin->checkAccess('export');

    //     $format = $request->get('format');

    //     // // NEXT_MAJOR: remove the check
    //     // if (!$this->has('sonata.admin.admin_exporter')) {
    //     //     @trigger_error(
    //     //         'Not registering the exporter bundle is deprecated since version 3.14. You must register it to be able to use the export action in 4.0.',
    //     //         \E_USER_DEPRECATED
    //     //     );
    //     //     $allowedExportFormats = (array) $this->admin->getExportFormats();

    //     //     $class = (string) $this->admin->getClass();
    //     //     $filename = sprintf(
    //     //         'export_%s_%s.%s',
    //     //         strtolower((string) substr($class, strripos($class, '\\') + 1)),
    //     //         date('Y_m_d_H_i_s', strtotime('now')),
    //     //         $format
    //     //     );
    //     //     $exporter = $this->get('sonata.admin.exporter');
    //     // } else {
    //         $adminExporter = $this->get('sonata.admin.admin_exporter');
    //         $allowedExportFormats = $adminExporter->getAvailableFormats($this->admin);
    //         $filename = $adminExporter->getExportFilename($this->admin, $format);
    //         $exporter = $this->get('sonata.exporter.exporter');
    //     // }

    //     if (!\in_array($format, $allowedExportFormats, true)) {
    //         throw new \RuntimeException(sprintf(
    //             'Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`',
    //             $format,
    //             $this->admin->getClass(),
    //             implode(', ', $allowedExportFormats)
    //         ));
    //     }

    //     return $exporter->getResponse(
    //         $format,
    //         $filename,
    //         $this->admin->getDataSourceIterator()
    //     );
    // }

Julien Jorry committed
178 179 180
    public function deleteAction($id)
    {
        $request = $this->getRequest();
181 182
        $id = $request->get($this->admin->getIdParameter());
        $object = $this->admin->getObject($id);
Julien Jorry committed
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

        if (!$object) {
            throw $this->createNotFoundException(sprintf('unable to find the object with id: %s', $id));
        }

        $currentUserId = $this->getUser()->getId(); // ID of the current user
        if ($currentUserId == $id) {
            $this->addFlash(
                'sonata_flash_error',
                'Vous ne pouvez pas supprimer votre compte !'
            );

            return $this->redirectTo($object);
        }
        if ($object->hasRole('ROLE_SUPER_ADMIN') || $object->hasRole('ROLE_ADMIN_SIEGE')) {
            $this->addFlash(
                'sonata_flash_error',
                'Vous ne pouvez pas supprimer le compte admin !'
            );

            return $this->redirectTo($object);
        }

        return parent::deleteAction($id);
    }

    public function batchActionDelete(ProxyQueryInterface $query)
    {
211
        $request = $this->getRequest();
Julien Jorry committed
212 213 214 215 216 217 218 219 220 221 222
        $currentUserId = $this->getUser()->getId(); // ID of the current user
        $selectedUsers = $query->execute();

        foreach ($selectedUsers as $selectedUser) {
            if ($selectedUser->getId() == $currentUserId) {
                $this->addFlash(
                    'sonata_flash_error',
                    'Vous ne pouvez pas supprimer votre compte !'
                );

                return new RedirectResponse(
223
                    $this->admin->generateUrl('list', ['filter' => $this->admin->getFilterParameters()])
Julien Jorry committed
224 225 226 227 228 229 230 231 232
                );
            }
            if ($selectedUser->hasRole('ROLE_SUPER_ADMIN') || $selectedUser->hasRole('ROLE_ADMIN_SIEGE')) {
                $this->addFlash(
                    'sonata_flash_error',
                    'Vous ne pouvez pas supprimer le compte admin !'
                );

                return new RedirectResponse(
233
                    $this->admin->generateUrl('list', ['filter' => $this->admin->getFilterParameters()])
Julien Jorry committed
234 235 236 237 238 239
                );
            }
        }

        return parent::batchActionDelete($query);
    }
240

241 242 243 244 245 246 247 248 249
    /**
     * Sets the admin form theme to form view. Used for compatibility between Symfony versions.
     */
    private function setFormTheme(FormView $formView, ?array $theme = null): void
    {
        $twig = $this->get('twig');

        $twig->getRuntime(FormRenderer::class)->setTheme($formView, $theme);
    }
Julien Jorry committed
250
}