A
A
Artemio Vegas2018-05-08 06:31:47
symfony
Artemio Vegas, 2018-05-08 06:31:47

Symfony, redirect user in case of absence of any information in the database?

Welcome all!
The situation is as follows, In the controller there is an action in which the form for creating a task. One of the form fields is "Category" - a drop-down list from the Category entity.
Now I have a check in the controller (we make a request to the database and check if it has categories) that if the user does not have created categories, then we redirect him to create a category.
But checking in the controller is somehow not according to Feng Shui.
I want to make a listener / subscriber for this, tell me which event to subscribe to? kernel.request?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
voronkovich, 2018-05-08
@ArtemioVegas

The subscriber would be useful if the validation logic was duplicated across multiple controllers. And so ... I see no reason to make a subscriber. I would just move the check into a separate controller method and that's it.

public function redirectIfNoCategoriesFound(): ?RedirectResponse
{
    if ($this->getDoctrine()->createQuery('SELECT EXISTS ...')->getSingleScalarResult()) {
        $this->setFlash('message', 'Сначала вам нужно создать категорию.');

        return $this->redirectToRoute('new_category');
    }
}

Why? What is the principle of MVC/SOLID/etc. violated?
UPD. If you still decide to use events, it's better to subscribe to the kernel.controller event to find out the name of the controller. See https://symfony.com/doc/current/event_dispatcher/b...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question