How to add target to form in Symfony2 - php

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

Related

How make two form in same controller [Symfony]

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()]);
}
}

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);
}
});

Search filter with method get doesn't found results [symfony2]

I have a search form that works with the method POST, but the method POST doesn't display the requested data in the url.
With method POST the url look like this:
/search_flight
with the method GET no results found, the url look like this:
/search_flight?from=Cape+Town%2C+International+CPT&to=Johannesburg%2C+O.R.+Tambo+International+JNB&departuredate=2016%2F01%2F08&arrivaldate=2016%2F10%2F04&price=57.5%2C1000
I also noticed that with the method GET the data is reset in each input of the form.
routing.yml
searchFlight:
path: /search_flight
defaults: { _controller: FLYBookingsBundle:Post:searchtabflightResult }
requirements:
_method: GET|POST
controller
This method send the requested data to the method searchtabflightResultAction that will handle the query.
public function searchtabflightAction()
{
//$form = $this->createForm(new SearchflightType(),null, array('action' => $this->generateUrl('searchFlight'),'method' => 'GET',));
$form = $this->get('form.factory')->createNamed(null, new SearchflightType());
return $this->render('FLYBookingsBundle:Post:searchtabflight.html.twig', array(
'form' => $form->createView(),
));
}
.
<form action="{{ path ('searchFlight') }}" method="GET">
{# here I have my forms #}
</form>
.
public function searchtabflightResultAction(Request $request)
{
//$form = $this->createForm(new SearchflightType());
$form = $this->get('form.factory')->createNamed(null, new SearchflightType());
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
$airport1 = $form["to"]->getData();
$airport = $form["from"]->getData();
$departureDateObj = $form["departuredate"]->getData();
$arrivalDateObj = $form["arrivaldate"]->getData();
$price = $form["price"]->getData();
$entities = $em->getRepository('FLYBookingsBundle:Post')->searchflight($airport1,$airport,$departureDateObj,$arrivalDateObj,$price);
return $this->render('FLYBookingsBundle:Post:searchtabflightResult.html.twig', array(
'entities' => $entities,
'form' => $form->createView(),
));
}
How can I make my search filter works with method get ?
Everything should be done within two actions, the basic concept is:
SearchFlightType has with/wo price option:
class SearchFlightType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('from', FormType\TextType::class)
->add('to', FormType\TextType::class)
->add('departuredate', FormType\TextType::class)
->add('arrivaldate', FormType\TextType::class);
if ($options['price']) {
$builder->add( 'price', FormType\TextType::class );
}
$builder
->add('submit', FormType\SubmitType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'price' => false,
));
}
}
Controller.php
class PostController extends Controller
{
/**
* #Route("/index", name="index")
*/
public function indexAction(Request $request)
{
$defaultData = array();
$form = $this->createForm(SearchFlightType::class, $defaultData, array(
// action is set to the specific route, so the form will
// redirect it's submission there
'action' => $this->generateUrl('search_flight_result'),
// method is set to desired GET, so the data will be send
//via URL params
'method' => 'GET',
));
return $this->render('Post/searchtabflight.html.twig', array(
'form' => $form->createView(),
));
}
/**
* #Route("/search_flight_result", name="search_flight_result")
*/
public function searchTabFlightResultAction(Request $request)
{
$defaultData = array();
$entities = null;
$form = $this->createForm(SearchFlightType::class, $defaultData, array(
// again GET method for data via URL params
'method' => 'GET',
// option for price form field present
'price' => true,
));
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// get data from form
$data = $form->getData();
// process the data and get result
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('FLYBookingsBundle:Post')->searchflight($data['from'], $data['to'], ...);
}
return $this->render('Post/searchtabflight.html.twig', array(
'form' => $form->createView(),
// present the result
'entities' => $entites,
));
}
}

Symfony 2 isClicked on submit buttons always returning FALSE

I'm trying to implement two submit buttons to my form. My form looks something like this.
Form:
public function buildForm(\Symfony\Component\Form\FormBuilderInterface $builder, array $options) {
$builder
// ...
->add('gateway', 'submit', array(
'label' => 'Go to payment gateway',
))
->add('save', 'submit', array(
'label' => 'Save order',
));
parent::buildForm($builder, $options);
}
Method $form->get('save')->isClicked() in controller always returning FALSE . It doesn't depend on which button I click in form, everytime returns FALSE.
Controller:
public function indexAction(Request $request) {
$form = $this->createForm(new OrderForm(null));
$form->handleRequest($request);
if ($form->isValid()) {
$values = $form->getData();
$action = $form->get('save')->isClicked() ? 'front.order.success' : 'front.order.gateway';
if ($action == 'front.order.success') {
//save order
} else if ($action == 'front.order.gateway') {
//something else
}
}
return $this->redirect($this->generateUrl($action));
}
Have you any idea why? Thank you for answers.

Categories