Pre Fill Symfony Form Text Field with Data From the Database - php

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.

Related

Symfony2 - customizing FormType classes

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.

Get data from database not from form

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!

Symfony2 Saving data of related Entity after submiting form

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.

CakePHP prepopulate form with data from a link

Assume I'm in my items controller.
Ok say I am in my view action (the url would be something like /items/view/10012?date=2013-09-30) which lists a list of items that belongs to a client on a given date.
I want to link to add a new item. I would use the htmlhelper like so:
echo $this->Html('action'=>'add');
In my add action I have a form which has fields like client_id and item_date.
When I'm in my view action I know these values as I am viewing the items for a specific client on a specific date. I want to pass these variables to my add action so it will prefill those fields on the form.
If I add a query string in my link ('?' => array('client_id'=>$client_id)) it breaks the add action as it will give an error if the request is not POST. If I use a form->postLink I get another error as the add action's POST data must only be used for adding the record, not passing data to prefill the form.
I basically want to make my link on the view page pass those 2 variables to the add action in the controller so I can define some variables to prefill the form. Is there a way to do this?
Here is my add controller code. It may differ in content a bit from my question above as I have tried to simplify the question a bit but the concept should still apply.
public function add(){
if ($this->request->is('post')) {
$this->Holding->create();
if ($this->Holding->save($this->request->data)) {
$this->Session->setFlash(__('Holding has been saved.'), 'default', array('class' => 'alert alert-success'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to add your holding.'), 'default', array('class' => 'alert alert-danger'));
}
$this->set('accounts', $this->Holding->Account->find('list'));
$sedol_list = $this->Holding->Sedol->find('all', array(
'fields' => array(
'id', 'sedol_description'
),
'recursive' => 0,
'order' => 'description'
)
);
$this->set('sedols', Hash::combine($sedol_list, '{n}.Sedol.id', '{n}.Sedol.sedol_description') );
}
Why not use proper Cake URL parameters?
echo $this->Html->link('Add Item', array(
'action' => 'add',
$client_id,
$item_date
));
This will give you a much nicer URL like:
http://www.example.com/items/add/10012/2013-09-30
And then in your controller, you modify the function to receive those parameters:
public function add($client_id, $item_date) {
// Prefill the form on this page by manually setting the values
// in the request data array. This is what Cake uses to populate
// the form inputs on your page.
if (empty($this->request->data)) {
$this->request->data['Item']['client_id'] = $client_id;
$this->request->data['Item']['item_date'] = $item_date;
} else {
// In here process the form data normally from when the
// user has submitted it themselves...
}
}

Codeigniter - How to populate form from database?

I have a small site which allows a user to enter values in a form and then either submit it directly or store the field values in a template to later submit it. To submit the form later, he can load the previously saved template. For that there are three buttons Load Template / Save Template / Submit form.
Because i am using the form validation built-in functionality from Codeigniter i run into problems when i want to populate the form with a template, which had been previously stored.
The form fields are all set up like
$name = array(
'name' => 'name',
'id' => 'name',
'value' => set_value('name', $form_field_values['name'])
);
The variable $form_field_values holds the values from either a loaded template in the case when a template has been loaded or the default values when the form is first loaded.
Initially the form is loaded with the default values. When i click on Load Template the values from the template are not chosen by set_value() because there were the default values in there before. What i want is to replace the values of the form fields with the ones from the template.
Do you have any idea how to do that in a clean approach? What i have done is to introduce a variable to skip the call to set_value() completely like:
$name= array(
'name' => 'name',
'id' => 'name',
'value' => $skip_form_validation ? $form_field_values['name'] : set_value('name', $form_field_values['name'])
);
Where $skip_form_validation is a variable set in the controller, based on what button was pressed. Form validation is skipped for saving/loading a template.
Codeigniter's set_value() function is a simple function which finds value in $_POST if value found then return else returns second argument, you can remove set_value() and write your own code for it. you can write $_POST['field_name'] if you want to populate value of POST data or add whatever value you want to add
Just use like this
$name = array(
'name' => 'name',
'id' => 'name',
'value' => $valueFromYourTemplate
);
You don't need to use set_value() function if you don't want to set POST values in the form
Assuming you retrieve the database fields and pass them to a data array in your controller.
$record = $this->data_model->get_record(array('uid' => $user_id), 'users');
if (!is_null($record)) {
$data['uname'] = $record->username;
$data['loc'] = $record->location;
}
where 'users' is the database table, and the uid is the id field of the table users.
In your form, do something like this
Hope it helps!

Categories