Symfony2 - Reset form field after submission - php

I wonder whether there is a simple way to reset one of the form fields after form submission and then pass the form to the view - to render the same form but one of the field will be with it's default value. Something like:
$form = $this->createForm('MyForm');
$form->handleRequest($request);
if ($form->isValid()) {
// do something
// ...
// reset one of the form field to it's default value
// something like:
// $form->field->reset() or
// $form->field->setValue('');
}
return array(
'form' => $form->createView(),
);
Thanks!

You can use:
$form->get('field')->submit($defaultValue);
Check out the doc.

Related

Edit entity part with form

I have an entity (about 20/25 fields) and i want to edit it with a form.
I just want to edit (and display) few form field.
The problem is, all fields displayed are correctly update, but fields that are not rendered are update with "null" value by default.
My controller :
$em = $this->getDoctrine()->getManager();
$LaboRequest= $em->getRepository('MyBundle:LaboRequest')->find($id);
$form = $this->createForm('MyBundle\Form\LaboRequestType', $LaboRequest);
if ($request->isMethod('POST') && $form->handleRequest($request)->isSubmitted() && $form->isValid()) {
$em->persist($LaboRequest);
$em->flush();
return $this->redirectToRoute(...);
}
return $this->render('...', array(
'LaboRequest' => $LaboRequest,
'form' => $form->createView(),
));
I only render few fields in my view, so i can understand, by default symfony use "null" for fields that are not render.
But is there a way to edit a part of an entity and not affect data of the entity with "null" value ?
I'm not sure you can do that.
But you can extend your original form and call
$builder->remove('xxx')
for each field you want to remove

Pre Fill Symfony Form Text Field with Data From the Database

How can I pre fill a text field in symfony with data from the database. I have a field in the host table called hostFee and when I create the form I want that data to pre fill this text field.
I am creating a form for new BookingSpecsType()...
Here is my form builder element.
$builder->add('hostFee', 'text', array(
'required'=>false,
'error_bubbling'=>true,
'label'=>'Do you charge a hosting fee?',
'data' => '??????? (How do I fill this text field dynamically with the Host table hostFee column data) ?????',
'attr'=>array(
'placeholder'=>'If yes, enter dollar amount $0.00',
'class'=>'form-control'
)
));
Thanks.
The documentation provide many examples.
When you use $this->createForm in your Controller action, the second parameter, allow you to hydrate the form with an object.
For example:
public function editAction()
{
$user = $this->getDoctrine()->getRepository('User')->find(1); // YOUR OBJECT RETRIEVED FROM THE DB FOR EXAMPLE
$form = $this->createForm(new EditType(), $user, array(
'action' => $this->generateUrl('account_edit'),
));
return $this->render(
'AcmeAccountBundle:Account:edit.html.twig',
array('form' => $form->createView())
);
}
You do not need to define manally the data. If you just init the form from an hydrated entity, then all data are init into all fields.

Validation of a form before submission

Using Symfony, version 2.3 and more recent, I want the user to click on a link to go to the edition page of an already existing entity and that the form which is displayed to be already validated, with each error associated to its corresponding field, i.e. I want
the form to be validated before the form is submitted.
I followed this entry of the cookbook :
$form = $this->container->get('form.factory')->create(new MyEntityFormType, $myEntity, array('validation_groups' => 'my_validation_group'));
$form->submit($request->request->get($form->getName()));
if ($form->isValid()) {
...
}
But the form is not populated with the entity datas : all fields are empty. I tried to replace $request->request->get($form->getName()) with $myEntity, but it triggered an exception :
$myEntity cannot be used as an array in Symfony/Component/Form/Extension/Csrf/EventListener/CsrfValidationListener.php
Does anyone know a method to feed the submit method with properly formatted datas so I can achieve my goal ? Note : I don't want Javascript to be involved.
In place of:
$form->submit($request->request->get($form->getName()));
Try:
$form->submit(array(), false);
You need to bind the the request to the form in order to fill the form with the submitted values, by using: $form->bind($request);
Here is a detailed explanation of what your code should look like:
//Create the form (you can directly use the method createForm() in your controller, it's a shortcut to $this->get('form.factory')->create() )
$form = $this->createForm(new MyEntityFormType, $myEntity, array('validation_groups' => 'my_validation_group'));
// Perform validation if post has been submitted (i.e. detection of HTTP POST method)
if($request->isMethod('POST')){
// Bind the request to the form
$form->bind($request);
// Check if form is valid
if($form->isValid()){
// ... do your magic ...
}
}
// Generate your page with the form inside
return $this->render('YourBundle:yourview.html.twig', array('form' => $form->createView() ) );

Change form value before Codeignighter Form Validation

I have form data posted by client, I want to manipulate one of the forms value before I run it through $this->form_validation->run().
Is this possible
i.e something like;
//Get user form inputs
$input = $this->input->post();
//generate slug - my custom code
$input['slug'] = sf_generate_slug($input['slug']);
if ($this->form_validation->run()) {
...
You can reassign any post value before $this->form_validation->run() like
$_POST['slug'] = sf_generate_slug($_POST['slug']);
While if you use your above method it will validate because it didn't overrides the $_POST values
Hope it makes sense

To create check box in symfony using widgets and also validate it?

the code in symfony that i am using,
$this->setWidgets(array(
'mobile' =>new sfWidgetFormInput(),
'subscribetosms' =>new sfWidgetFormInputCheckbox(),
));
i want to validate the checkbox, and also code to take values from check box
to validate form fields in symfony u need to set validators like this (assuming you are in a form class):
$this->setValidators(array(
'mobile' => new sfValidatorString(array(...)),
'subscribetosms' => new sfValidatorInteger(array(...))
));
Question is, what do you want to validate? If you want some kind of value send to your php script if the checkbox is selected you need to set this value in the widget.
new sfWidgetFormInputCheckbox(array('value_attribute_value'=>'your_value' )
Now you could configure your validator to validate this value (sfValidatorString for a string, of sfValidatorInteger for an integer).
To get the value in your action after the validation:
if ($this->form->isValid()) {
$myValue = $this->form->getValue('subscribetosms');
}

Categories