How make two form in same controller [Symfony] - php

I have a probleme, i want two forms in same controller
I have this controller with two forms, but the probleme is the form1 work good ( return new response) but form2 not working ..
what the solution?
public function fCandidat($id, Request $request)
{
$candidat = $this->getDoctrine()
->getRepository(Candidat::class)
->find($id);
$form = $this->createForm(CandidatType::class, $candidat);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
return new Response('form1');
}
$defaultData = ['message' => 'Demandes candidats'];
$form2 = $this->createFormBuilder($defaultData)
->add('demandes', DemandeType::class)
->add('send', SubmitType::class)
->getForm();
$form2->handleRequest($request);
if ($form2->isSubmitted() && $form2->isValid()) {
return new Response('form2');
return $this->render('index.html.twig', ['form' => $form->createView(), 'form2' => $form2->createView()]);
}
}

Related

Symfony - controller edit action

I defined the form in my controller and set function to edit/update specific fields that I can find by ID. I can't find what am I doing wrong..
public function getUserEdit(Request $request)
{
$form = $this->createFormBuilder()
->add('firstName', TextType::class, array('label' => 'First Name*', 'attr' => ['class'=>'form-control']))
->add('save', SubmitType::class, array('label' => 'Send', 'attr' => [
'class' => 'btn btn-primary action-save'
]))
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$firstName = $data['firstName'];
$this->container->get('user')->editUser($firstName);
}
return $this->success();
}
Service
public function editUser($id)
{
$editUsers = $this->getUserRepository()->find($id);
if(empty($editUsers)) {
$editUsers = new User();
$editUsers->setId($id);
$this->em->persist($editUsers);
$this->em->flush();
}
}
Symfony returns a single object when searching by find primary key (usually id), then you can check if exist returns a single Entity (in this case User) and so that checking by using insteance.
public function editUser($id)
{
$editUsers = $this->getUserRepository()->find($id);
if($editUsers insteance User) { // here just check
//$editUsers = new User(); // here You don't need create new object of class User, just remove
$editUsers->setId($id);
$this->em->persist($editUsers);
$this->em->flush();
}
else {
// do something if you need
}
}

Best practice for changing default parameter of form object after getForm() symfony2.8

I updated and summurized the question.
What I want to do is changing the default value of form object after getForm()
public function newAction(Request $request)
{
$task = new Task();
$form = $this->createFormBuilder($task)
->add('task', TextType::class,array('data' => 'default text data') // Set the default data for loaded first time.
->add('save', SubmitType::class, array('label' => 'Save'))
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//I want change the default value of task, I tried a few methods.
$d = $form->getData();
$form->get('task')->setData('replace text data'); // not work
$d->setData('second data'); // notwork
}
Is it possible or how??
Try this one.
$builder->addEventListener(FormEvents::POST_SUBMIT, function(FormEvent $even) {
$data = $event->getData();
$form = $event->getForm();
if (isset($data['task'])) {
$data['task'] = "Default Task1";
$event->setData($data);
}
});

Passing posted values from one action to another in the same controller in symfony

I have 2 actions in the same controller.
I find problem in passing posted values from the 1st action to the the 2nd one.
I tried to use forward method http://symfony.com/doc/current/controller/forwarding.html
BTW both actions (the 'forwarding' and the 'forwarded to') have forms with submissions.
Problem is I couldn't access the variable " $param1 " in the second action. It always goes null.
Is there anything I have missed here?
Here is my code:
This is the 1st action:
/**
*
* #Route("/new1", name="command_check1")
*/
public function check1Action(Request $request)
{
$host = new Host();
$form = $this->createFormBuilder($host)
->add("iPaddress", TextType::class)
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$a= $form["iPaddress"]->getData(); //$a= '127.0.0.1'
**$this->forward('AcmeBundle:Command:check2', array('param1' => $a));**
if($this->pingAction($a)==true){
return $this->redirectToRoute('command_check2'); }
}
return $this->render('host/new1.html.twig', array(
'host' => $host,
'form' => $form->createView(),));
}
This is the 2nd action:
/**
*
* #Route("/new2", name="command_check2")
*/
public function check2Action(Request $request, **$param1**)
{
**var_dump($param1); // here i can get the posted value $param1= '127.0.0.1'**
$host = new Host();
$form = $this->createFormBuilder($host)
->add("login", TextType::class)
->add("password", TextType::class)
->getForm();
$form->handleRequest($request);
**var_dump($param1); // until here it works good $param1= '127.0.0.1'**
if ($form->isSubmitted() && $form->isValid())
{
**// the problem is here after submitting the 2nd form
var_dump($param1); // $param= null**
$b= $form["login"]->getData();
$c= $form["password"]->getData();
}
return $this->render('host/new2.html.twig', array(
'host' => $host,
'form' => $form->createView(),));
}
Firstly, Forward is only necessary trough different controllers, in the same controller instead of make a forward simply call the other action:
$this->check2Action($request, $a);
In the other hand based on your approach is nos necessary make a forward or call to the check2Action.
This is my recommendation based on your example, (non tested code)
/**
*
* #Route("/new1", name="command_check1")
*/
public function check1Action(Request $request)
{
$host = new Host();
$form = $this->createFormBuilder($host)
->add("iPaddress", TextType::class)
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$a = $form["iPaddress"]->getData(); //$a= '127.0.0.1'
if($this->pingAction($a)==true){
return $this->redirectToRoute('command_check2', ['ip' => $a]);
}
}
return $this->render('host/new1.html.twig', array(
'host' => $host,
'form' => $form->createView(),));
}
Action2:
/**
*
* #Route("/new2/{ip}", name="command_check2")
*/
public function check2Action(Request $request, $ip)
{
$host = new Host();
$form = $this->createFormBuilder($host)
->add("login", TextType::class)
->add("password", TextType::class)
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
var_dump($ip);
$b= $form["login"]->getData();
$c= $form["password"]->getData();
}
return $this->render('host/new2.html.twig', array(
'host' => $host,
'form' => $form->createView(),));
}
In the above example the IP submitted in the action1 is passed as argument to check2 redirect, then the submission of action2 is taken with this IP and is always available.

How to add target to form in Symfony2

I am trying to add target to form.
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('email', 'email', array('label' => 'Adres email'),'attr' => array('class' => 'class_name'))}
In controller I use:
$Register = new Register();
$form = $this->createForm(new RegisterType(), $Register);
$form -> handleRequest($Request);
just pasting some code i use, i defined the formType as service with tag "review" for my Review Entity, heres my controller action
$review = new Review();
$form = $this->createForm('review',$review);
$request = $this->getRequest();
// only handle request if form is submitted
if ('POST' === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
$entity=$form->getData();
try {
$saved=$this->myService->saveReview($entity);
} catch (\Exception $e) {
$form->addError(new FormError($e->getMessage()));
return array(
"form"=>$form->createView()
);
}
return $this->redirect($this->generateUrl('some.url',array("some","mandatory-params")));
}
}
return array(
"form"=>$form->createView(),
);
http://symfony.com/doc/current/cookbook/form/create_form_type_extension.html

Symfony2 How to process dynamic embed forms collection?

I try this cookbook about embed form:
http://symfony.com/doc/current/cookbook/form/form_collections.html
But the embed foreign key (task_id field in Tag table) is not save, always NULL
Here the complete code: https://gist.github.com/1755140
Do you know why?
Thank
Edit::
My trouble was in process form action. Like the tag form is embed dynamically, so i don't know how many tag(s) i will have. If i add in createAction
$tag1 = new Tag();
$task->addTags($tag1);
only the first embed form was correctly save! How to save the other tags?
public function createAction(Request $request)
{
$task = new Task();
$tag1 = new Tag();
$task->addTags($tag1);
$form = $this->createForm(new TaskType(), $task);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($task);
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
return array(
'form' => $form->createView()
);
}
Edit2:
My solution which resolve the trouble, what do you think about it? Better?
public function createAction(Request $request)
{
$task = new Task();
$tasks = $request->request->get('task', array());
if (isset($tasks['tags'])) {
$tags = $tasks['tags'];
foreach($tags as $tag) {
$tag = new Tag();
$task->addTags($tag);
}
}
$form = $this->createForm(new TaskType(), $task);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($task);
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
return array(
'form' => $form->createView()
);
}
Edit3:
A much better alternative (not tested again)
http://www.siteduzero.com/tutoriel-3-523899-creer-des-formulaires-avec-symfony2.html#ss_part_2
public function createAction(Request $request)
{
$task = new Task();
$form = $this->createForm(new TaskType(), $task);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($task);
foreach($task->getTags() as $tag) {
$em->persist($tag);
}
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
return array(
'form' => $form->createView()
);
}
In TaskController on line 29 try to use $task->addTags($tag1); instead of $task->getTags()->add($tag1);
I don't understand. Is this solution wrong?
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
foreach($task->getTags() as $tag) {
$tag->setTask($task);
}
$em->persist($task);
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
It works and it seems simpler.

Categories