Symfony Form/Templating good practice

Please evaluate code below and advice for better practice. Am I correct? and that if (!empty($_POST)) is a good practice? please advice for better way to handle this. and how to call controller methods for crud? do I need router for this?

use Symfony\Component\Form\Forms;
use Symfony\Component\Form\Extension\Csrf\CsrfExtension;
use Symfony\Component\Form\Extension\Csrf\CsrfProvider\SessionCsrfProvider;
use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationExtension;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Templating\PhpEngine;
use Symfony\Component\Templating\TemplateNameParser;
use Symfony\Component\Templating\Loader\FilesystemLoader;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Type;

$csrfSecret = md5(unique_id());
$session = new Session();
$csrfProvider = new SessionCsrfProvider($session, $csrfSecret);

$formFactory = Forms::createFormFactoryBuilder()
    ->addExtension(new HttpFoundationExtension())
    ->addExtension(new CsrfExtension($csrfProvider))
    ->getFormFactory();


$defaults = array(
    'dueDate' => new \DateTime('tomorrow'),
);

$form = $formFactory->createBuilder('form', $defaults)
    ->add('task', 'text', array(
        'constraints' => new NotBlank(),
    ))
    ->add('dueDate', 'date', array(
        'constraints' => array(
            new NotBlank(),
            new Type('\DateTime'),
        )
    ))
    ->getForm();

$loader = new FilesystemLoader(__DIR__.'/views/%name%');
$templating = new PhpEngine(new TemplateNameParser(), $loader);


if (!empty($_POST)) {

   // render form
   echo $templating->render('formpage.php', array('form' => $form->createView());

} else {
 
   $errorsAsArray = iterator_to_array($form->getErrors());
   if (!empty($errorsAsArray)) {

       // back to form with error messages
       echo $templating->render('formpage.php', array('form' => $form->createView(), 'errors' => $errorsAsArray);

   } else {

      // process submitted data

      $request = Request::createFromGlobals();
      $form->handleRequest($request);

      if ($form->isValid()) {
          $data = $form->getData();

          // ... perform some action, such as saving the data to the database
          echo $templating->render('listingpage.php', array('message' => 'Done Successfully');
      }
   }
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.