How to pass variable from controller to form In Symfony?

It will be the complex and time-consuming process to create software applications, however, utilizing a right framework can help you to develop software faster(by reusing code in form of components and modules), and will work better. There are so many PHP frameworks that are based on the MVC design pattern. Today we are going to discuss on one of them know as “SYMFONY”. In current scenario “SYMFONY” is one the fastest framework that PHP had. It provides a large amount of functionality and security with less code. Today we are going to learn, How to pass variable from controller to form In Symfony?

We have to create two files to achive this.

1) Controller file
2) Form File

Controller File:

Suppose I already have a bundle called Test. So I need to create the controller file inside the following location.

Location:

src/TestBundle/Controller/ExampleController.php

Code:

<?php
namespace Projectname\TestBundle\Controller;
class ExampleController extends Controller
{
    public function newAction(Request $request, $id = '')
    {
       $objName = $em->getRepository('ProjectnameTestBundle:Example')->find($id);
       $data = array(
                       "value1" => intval($_GET['value1']),
                       "value2" => intval($_GET['value2']),
                       "value3" => intval($_GET['value3']),
                       "value4" => intval($_GET['value4']),
               );
      $form = $this->createForm(new ExampleFormType($data), $objName);
      // This statement will pass the variable value to form using constructor.
   }
}
?>

Form File:

Location:

src/TestBundle/Form/Type/ExampleFormType.php

Code:

<?php
namespace Projectname\TestBundle\Form\Type;
class ExampleFormType extends AbstractType {
    public $data = array();
    public function __construct($data) {
         $this->data = $data;  // Now you can use this value while creating a form field for giving any validation.
    }
}
?>

Leave a Reply