I'm having a problem when trying to compare a data database, with data input by form.
I have a "pedido", this has many "items". I need compare "item" by "item" if this is modifies in the form.
Then I need get original data from database and data modified from form.
The problem is when i try get original data from database.
Always get the data modified by form.
How Can i get the original data from database after the submit the form?
NOTE: i have tried get PedidoAuxiliar before and after HandleRequest.This doesn´t work!
UPDATE CODE: Input how compare the items
This is my controller editAction:
public function editarAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$pedido = $em->getRepository('PedidosBundle:Pedido')->find($id);
//$pedidoAuxiliar = $em->getRepository('PedidosBundle:Pedido')->find($id);
$formulario = $this->createForm(new PedidoType(), $pedido, array(
'action' => $this->generateUrl('my_routing', array('id' => $id)),
'attr' => array(
'novalidate' => 'novalidate'
),
'method' => 'POST',
));
$formulario->handleRequest($request);
if($formulario->isValid()){
$pedidoAuxiliar = $em->getRepository('PedidosBundle:Pedido')->find($id);
foreach($pedido->getArticulos() as $articulo){
foreach($pedidoAuxiliar->getArticulos() as $articuloAuxiliar){
if($articuloAuxiliar->getId() == $articulo->getId()){
if($articuloAuxiliar->getCantidad() == $articulo->getCantidad()){
//Some code...
To get data from db u can use EntityManager::refresh($entity) its overwrite entity data using db. So u must use data from form, not entity to compare.
But u always can ust Doctrine to check changes eg: http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/change-tracking-policies.html
because Doctrine hold info about old and new value, but is not so easy to get (outside listeners)
I have found a solution. I have created a new connection entity manager in my config.yml.
Now I call my entity data from my new entity manager and i get datas from database! Thanks!
Related
I have created a search form in which I use to search my database to produce some result.
using the below in a my forms directory as a form class I generate the form.
$builder->add(
'startDate',
DateType::class,
[
'label' => 'start date',
'format' => 'yyyy-MM-dd',
'required' => true,
'constraints' => [
new Constraints\NotBlank(),
new Constraints\DateTime(),
],
]
);
in my controller I already have retrieved the data using the getData() method
$form = $this->createForm(testForm::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$start = date_format($form->get('start')->getData(), 'Y-m-d');
At the moment I want to get this data using a class object
e.g like this
$form = $this->createForm(testForm::class, $classobject);
$form->handleRequest($request);
where I would use the class object to retrieve the posted data from the form class "testForm"
how have I tried to solve this on my own?
I tried reading tutorials on this concept e.g as below
https://blog.martinhujer.cz/symfony-forms-with-request-objects/
note : this is a learning curve for me, I do not really grasp this concept
Please, constructive responses would be well appreciated.
Thanks
$form->getData() will return the object populated with the submited data. By default the Form Component returns an array, but if you pass an object as the second arg to createForm or set data_class option then you will get the object back.
I've a form with 120 fields to insert into the DB. The form is inserting fine and the approach I used is below:
I'm fetching all the fields from the view as below in the controller and passing the array($postdata) to the model file to insert.
**View**
$postdata = array(
'firstname' => $this->input->post('firstname'), //1st field
'lastname' => $this->input->post('lastname'), // 2nd field
'age' => $this->input->post('age'),
....
....
'test' => $this->input->post('test') // 120th field.
);
$this->Form_Model->insertdata($postdata);
**Model:**
function insertdata($data = array()) {
$sql_query = $this->db->insert('form_insert', $data);
redirect('Form');
}
My question is Is there any better way to insert. This approach feels bit repetitive.
If you simply want to get an array of all the data submitted, you can do it like this:
$postdata = $this->input->post();
This means, all the data submitted from the form will be there in this array.
And if you want to remove any particular element from this array, you can use unset().
Say for example, you may have named your submit button as "submit_btn" like this:
<input type="submit" name="submit_btn" />
then this value would be there in the above returned array. You can remove it like this:
$postdata = $this->input->post();
unset( $postdata['submit_btn']);
Btw, I have a couple of suggestions. The logic part is done in a Controller(you referred it by mistake as View). A View is simply for the displaying. And the Model is for the database communication.
Also, it would always be better to do some validations on the input that you received from the User through form submissions. We may don't even know what data they are sending!
And move that redirect() you used in the Model to the Controller from where you were trying to call that insertdata() method. In that Model, you just return a value (true or false or maybe something else) and do the business logic inside the Controller
You were kind of mixing up everything. That's why I thought to give you some pointers to help you.
Hope it helps :)
I have few cases where I need to ugly customizing of my FormType classes.
First one is that I need to check if the state of user is active in this case disable possibility to edit username. But just adding disabled atribute is not protecting input to be not submitted. So I decided not to show username input field. I achieved it by passing boolean through options.
Controller:
$userForm = $this->createForm(UserType::class, $user, array(
'is_active' => ($user->getState() == 'active')
));
And then in UserType class:
if ($options['is_active']) {
$builder
->add('username', EmailType::class);
}
$builder
->add('firstName', TextType::class),
...
Second case is that I need to remove NotBlank() constraint and add 'required' => false attribute from FileType field when profile photo is uploaded. I achieved it in similar way by passing boolean through options.
Controller:
$userForm = $this->createForm(UserType::class, $user, array(
'is_uploaded' => !empty($photo)
));
UserType class:
// achieved same way as previous problem
My questions would be:
What recommendations would be dealing with these kind of cases?
Is what I did correct and acceptable?
Is there a documentation or examples dealing with any of these cases?
You can move all this form configuration's logic into the form class.
Since you pass $user entity into the form with:
$userForm = $this->createForm(UserType::class, $user, array( // <- $user is passed
'is_uploaded' => !empty($photo)
));
You can access it in builForm method with:
$user = $builder->getData();
Then you can verify all the condifions inside the form and there's no need for making mess in controller.
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.
I'm starting developing with Symfony2 and looks like I need help. I have Product entity related with SynchronizationSetting entity. I can edit product data by form maped with his entity. But I also need to modify some data related to product in SynchronizationSetting. To do that I've modified the form so it look like that (Vendor\ProductBundle\Form\ProductType.php):
...
->add('synchronization_setting', 'choice', array(
'choices' => array('daily' => 'Daily', 'weekly' => 'Weekly', 'never' => 'Never'))
After form is submitted selected checkbox values are passed to setSynchronizationSetting method in Product Entity. Then I do that (Vendor\ProductBundle\Entity\SynchronizationSetting.php):
public function setSynchronizationSetting($data)
{
$synchronizationSetting = new SynchronizationSetting();
$synchronizationSetting->setDaily(in_array('daily', $data) ? '1' : '0');
...
}
And now I need to somehow save those SynchronizationSetting entity into database. I read that calling entity manager from here is very bad practice so... how should I save this?
One possible way (I'm not sure if it's good practice)
public function setSynchronizationSetting($data)
{
$synchronizationSetting = new SynchronizationSetting();
$synchronizationSetting->setDaily(in_array('daily', $data) ? '1' : '0');
}
public function retSynchronizationSetting()
{
return $this->synchronizationSetting;
}
Then in your controller in place where you handle form data you call retSynchronizationSetting() and save entity using EntityManager.