Reputation: 421
I want to prefill form fields in symfony2. The URL looks like this
http://localhost/Symfony/web/app_dev.php/clearance/new?projectId=6
I want now to set projectId in the form to 6.
Here is my controller code
public function newclearanceAction(){
$request = $this->getRequest();
$id = $request->query->get('projectId');
echo $id; //this works, but how to send it to the form?????
$clearance = new Clearance();
$form = $this->createForm(new ClearanceType(), $clearance);
if ($request->getMethod() == 'POST'){
$form->bindRequest($request);
if($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($clearance);
$em->flush();
return $this->redirect($this->generateUrl('MyReportBundle_project_list'));
}
}
return $this->render('MyReportBundle:Clearance:new.html.twig',array('form'=>$form->createView()));
And here is the code for the form view
<form action="{{ path('MyReportBundle_clearance_new') }}" method="post" >
{{ form_errors(form) }}
{{ form_rest(form) }}
<input type="submit" />
</form>
Thanks for any help!
Upvotes: 2
Views: 3774
Reputation: 3353
This depends on whether your clearance entity has a project related to it. If it does you can do something like:
$request = $this->getRequest();
$id = $request->query->get('projectId');
$em = $this->getDoctrine()->getEntityManager();
$project = $em->getRepository("MyReportBundle:Project")->find($id)
$clearance = new Clearance();
$clearance->setProject($project);
$form = $this->createForm(new ClearanceType(), $clearance);
This will set the project on the clearance object and pass it through to the form.
Currently you cannot do a hidden field for an entity in Symfony2 so my current fix is to create a query builder instance and pass it to the form so that the form select for projects does not get ridiculous when you have 100's of projects. To do this in the action I add:
$request = $this->getRequest();
$id = $request->query->get('projectId');
$em = $this->getDoctrine()->getEntityManager();
$repo = $em->getRepository("MyReportBundle:Project");
$project = $repo->find($id)
//create the query builder
$query_builder = $repo->createQueryBuilder('p')
->where('p.id = :id')
->setParameter('id', $project->getId());
$clearance = new Clearance();
$clearance->setProject($project);
//pass it through
$form = $this->createForm(new ClearanceType($query_builder), $clearance);
and in the form class:
protected $query_builder;
public function __construct($query_builder)
{
$this->query_builder = $query_builder;
}
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('Your field')
// all other fields
// Then below the query builder to limit to one project
->add('project', 'entity', array(
'class' => 'MyReportBundle:Project',
'query_builder' => $this->query_builder
))
;
}
Upvotes: 4