Gather two return statements in one, in route in Silex

问题内容:

I have a (match) route in Silex that displays a form, and then process it with the action method which is localized on the same page (that’s why Im using a match route).

So I gotta render the form and redirect the user after submitting the form, but I’m kinda stuck because my action form is at the same route and I m resulting in having two return statements which seems pretty ugly.

My route for add-book :

$app->match('/admin/add-book', function (Request $request) use ($app) {
    if ($app['security.authorization_checker']->isGranted('ROLE_ADMIN')) {
        $book = new Book();
        $bookForm = $app['form.factory']->createBuilder(BookType::class, $book)->getForm();
        $bookForm->handleRequest($request);

        if ($bookForm->isSubmitted() && $bookForm->IsValid()) {
            $app['dao.book']->save($book);
            $app['session']->getFlashBag()->add('success', 'Le livre a bien été ajouté.');
            return $app->redirect($app['url_generator']->generate('admin'));
        }
        return $app['twig']->render('add-book.html.twig', array(
            'bookForm' => $bookForm->createView()
        ));
    }
})->bind('add-book');

and that’s my form just in case :

        {{ form_start(bookForm) }}
        {{ form_row(bookForm.category, { 'label': 'Catégorie' }) }}
        {{ form_row(bookForm.title, { 'label': 'Titre' }) }}
        {{ form_row(bookForm.summary, { 'label': 'Résumé' }) }}
        {{ form_row(bookForm.image_path, { 'label': 'Ajouter une image de couverture' }) }}
        {{ form_row(bookForm.pdf_path, { 'label': 'Ajouter un fichier PDF' }) }}
        {{ form_row(bookForm.description, { 'label': 'Description du livre (format, nombre de pages, date de dépôt...)' }) }}

        <div class="form-group">
            <input type="submit" class="add-article-button" value="Publier le livre"/>
        </div>

        {{ form_end(bookForm) }}

I was finding that pretty handy since I don’t have to make another route for the ‘action’ part, but I have now two return in my route. One guy told me once that its a bad idea to have multiple return statements, preferably, having one return that will do the job depending of the situation is better.

The Silex form doc also makes two return statements… so I’m a bit lost.

Its working good as it is but I’m just a bit worried about that ‘two return statements’ story.

Would I need to make another route for the form action part ? Should I leave it as it is ? I don’t see another way to go… thanks for the help.

问题评论:

    
It’s cleaner (and easier to debug and read) if you do one router for GET (that shows the form) and one route for POST (which handles the posted form).

原文地址:

https://stackoverflow.com/questions/47756441/gather-two-return-statements-in-one-in-route-in-silex

Tags:,

添加评论