Symfony2 empty BBDD on edit form - php

I have this forms + controllers http://pastebin.com/wLPyXvbj
They are working when I'm adding data to DB (new data) but I have troubles while editing, I explain here the best I can.
Case 1
I edit EVERY SINGLE FIELD, data is updated on DB OK.
Case 2
I try to edit FEW fields, only fields I want users to edit instead of editing everything. Fields that have been available for update are inserted into DB without problem, but the other fields, thoose which I didn't want users to modify instead of keeping the old values in DB (because they HAVEN'T changed), they all turn empty values.
So there is something wrong with "selective editing" instead of "all fields edit" but I can't find the problem... I can't make an all fields edit form because some of them are static, no edits.
This is the controller I'm using for the edit action, as you can see it is diferent from the newAction
public function agentupdateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$comments = new VtigerTicketcomments();
$session = $this->get("session");
$proyecto = $session->get('proyecto');
$assets = $session->get('assets');
$contacts = $em->createQuery('SELECT u.contactid, u.email, u.phone, u.mobile FROM WbsGoclientsBundle:VtigerContactdetails u')->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
foreach($assets as $a)
$uuids[$a['UUID']] = $a['UUID'];
$entity = $em->getRepository('WbsGoclientsBundle:VtigerTicketcf')->find($id);
$ticket = $entity->getId();
$solution = $ticket->getSolution();
$ticketcfForm = $this->createForm(new TicketcfType($uuids, $session->get('contacts'), $session->get('rol'), $session->get('tecnicos')), $entity);
$ticketcfForm->submit($request);
if($ticketcfForm->isValid())
{
$data = $ticketcfForm->getData();
if($ticket->getStatus() == 'Closed')
{
if(!$ticket->getSolution())
$ticket->setSolution($solution);
$workflow = new ComVtigerWorkflowtaskQueue();
$workflow->setTaskid('9');
$workflow->setEntityid('9x'.$id);
$workflow->setDoafter('0');
$em->persist($workflow);
$em->flush();
$hoy = new \DateTime();
if($ticketcf->getFReso() == null)
$ticketcf->setFReso($hoy->format('d-m-Y H:i:s'));
}
$em->persist($ticket);
$em->flush();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('tickets_show', array('id' => $ticket->getTicketNo())));
}
return $this->render('WbsGoclientsBundle:Tickets:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'rol' => $session->get('rol'),
'ticket_form' => $ticketForm->createView(),
));
}

Related

How to loop form/new entity in Symfony

I'm having an issue with looping a form in Symfony using while loop. When the user enters one student period and it matches a registration reiterate the form to let them enter a 2nd student period and then a 3rd. I'm not doing it correctly or could I reiterate entity=new Student(); to let them enter two entities .
public function createAction(Request $request){
$entity = new Student();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$student = $em->getRepository('AcmeDemoBundle:Payrollperiod')
->findOneBy([
'begindate'=>$form->get('beginDate')->getData(),
'lastdate'=>$form->get('lastDate')->getData()
]);
$registration = $em->getRepository('AcmeDemoBundle:Payrollweek')
->findBystartdateAndenddate(
$form->get('beginDate')->getData(),
$form->get('lastDate')->getData()
);
$counter = count($registration);
while($counter<=2) {
if ($student){
$this->addFlash('error', 'Duplicate error: Student Period already existed.' );
return $this->redirect($this->generateUrl('student'));
}
elseif ($registration){
foreach ($registration as $reg) {
$reg->setStudentid($entity);
}
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('payrollperiod'));
}
else{
$this->addFlash('error', ' does not match .');
return $this->redirect($this->generateUrl('student'));
}
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
}
Read the documentation here http://symfony.com/doc/current/reference/forms/types/form.html#allow-extra-fields on adding fields. Your UI/Front-end should created more fields when the user needs to add a second or more periods. I should generate proper Symfony form elements and then when you post, you can handle it like a standard form post, iterating over the Request since the periods will be submitted as an array.
I did something like this in the past I adding a new form row was an AJAX call to a template that described the form input fields so I wasn't having to craft form HTML in Javascript/jQuery. .append() the template results to the form-- post and process the request.

Zend Framework 2 - How to keep value in form fields ? on multiple record update?

I am working on zend framwork 2
I have created one module with two fields
1) Test1
2) Test2
Database structure for this :
db name : zend_test_db
db fields : config_key , config_value
I want to store like config_key = test1key and config_value : textbox
enter value
Multiple records store at a time.
below is my controller function :
public function indexAction()
{
$form = new ConfigurationForm();
$form->get('submit')->setValue('Save Settings');
$form->get('test1key')->setValue('test1key');
$form->get('test2key')->setValue('test2key');
$request = $this->getRequest();
if ($request->isPost()) {
$configuration = new Configuration();
$form->setInputFilter($configuration->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$configuration->exchangeArray($form->getData());
$this->getConfigurationTable()->saveConfiguration($configuration);
// Redirect to list of configuration
return $this->redirect()->toRoute('configuration');
}
}
return array('form' => $form);
}
Above code works fine on Add fields . I am able to insert those fields and stored as key and value
But i am not able to update this.
Hope its clear
Where do i make mistake ?
I am not able to comment as I have reputation less then 50. I think you are trying to say that you are able to insert the data in database but you are not able to update it.
This is happening because you are creating new model every time.
$configuration = new Configuration();
You should initialize it using id params.
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('configuration', array(
'action' => 'add'
));
}
try {
$configuration = $this->getConfigurationTable()->getConfiguration($id);
}
catch (\Exception $ex) {
return $this->redirect()->toRoute('configuration', array(
'action' => 'index'
));
}
Using this you will be able to update the data as well. For more reference you can check zend framework Album module. Here is the link
https://framework.zend.com/manual/2.2/en/user-guide/forms-and-actions.html
If this was not the problem then please let me know so that I can help you in this concern.

How to reset form in Symfony

How can I reset the form after submit? It's a simple search form where I show a field on the top and a table in the bottom that shows either the results based on the search or the whole list... but it does not reset, the search key remained...
/**
* #Route("/", name="plazas_index")
*/
public function indexAction(Request $request)
{
$form = $this->createForm('AppBundle\Form\BuscarType');
$form->handleRequest($request);
$repository = $this->getDoctrine()->getRepository('AppBundle:Plaza');
if ($form->isSubmitted() && $form->isValid()) {
$clave = $form['clave']->getData();
$query = $repository->createQueryBuilder('p')
->where('p.nombre LIKE :nombre')
->orWhere('p.localidad LIKE :localidad')
->setParameter('nombre', '%'.$clave.'%')
->setParameter('localidad', '%'.$clave.'%')
->orderBy('p.nombre', 'ASC')
->getQuery();
$plazas = $query->getResult();
$cant = count($plazas);
$this->addFlash($cant ? 'success' : 'warning', 'La búsqueda de '.$clave. ' ha producido '.$cant.' resultados');
//return $this->redirectToRoute('plazas_index');
}
else {
$plazas = $repository->findAll();
}
unset ($form);
$form = $this->createForm('AppBundle\Form\BuscarType');
$form->handleRequest($request);
return $this->render('admin/plazas/index.html.twig', array(
'plazas' => $plazas,
'buscar_form' => $form->createView(),
));
}
I can't redirect because I do the render at the end of the action...
Any help is welcome, thanks!!
Remove the second $form->handleRequest($request); line and you are good to go!
handleRequest takes the submitted POST or GET data and applies it to the form, so if you want a blank form then you shouldn't call that.

How to get user ID (FOSUserBundle) in form builder in Symfony2?

I'm quite new here, be patient, please.
I'm trying to make notice board project in Symfony2 using FOSUserBundle.
I try to get logged user id to put it into form created with form builder (and then to MySQL database).
One of attempts is:
public function createNoticeAction(Request $request)
{
$notice = new Notice();
$form = $this->createFormBuilder($notice)
->add("content", "text")
->add("user_id","entity",
array("class"=>"FOS/UserBundle/FOSUserBundle:", "choice_label"=>"id"))
->add("isActive", "true")
->add("category", "entity",
array("class" => "AppBundle:Category", "choice_label" => "name"))
->add("save", "submit", array("label" => "Save"))
->getForm();
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
$em->persist($notice);
$em->flush();
return $this->redirectToRoute('app_user_showuserpage');
}
I tried many solutions again and again and I get some error.
You already have the user object Symfony > 2.1.x
In you Controller like this:
$userId = $this->getUser()->getId();
...
$notice->setUserId($userId);
$em->persist($notice);
Don't ->add field in you FormBuilder, its not safely. Set this value in you Controller and don't ->add this field in FormBuilder
for symfony 3.2.13
have excelent solution (just because is working, but is dangerous if someone discover it in pure HTML)
1) first build YourFormType class.
add normal field in Forms/YourFormType.php (if not, formbuilder tell you that you passing smth not quite right (too many fields) ; -) )
$builder
->add(
'MyModelAddedById',
HiddenType::class,
[
'label' => 'echhh', //somehow it has to be here
'attr' => ['style' => 'display:none'], //somehow it has to be here
]
);
2) in your controller
public function addSomethingAction(Request $request){
$form = $this->createForm(MyModelFormType::class);
//set field value
$request->request->set("prodModelAddedById", $this->getUser()->getId());
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$product = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($product);
$em->flush();
$this->addFlash('success', 'record was added');
return $this->redirectToRoute('products');
}
return $this->render(
'default.add.form.html.twig',
[
'newprod' => $form->createView(),
]
);
}
explenation:
you are passing a field and variable to formbuilder (settig it already to default value!)
and important thing, becose of BUG in my opinion - you can't in your form type set method:
public function getBlockPrefix()
{
//return 'app_bundle_my_form_type';
}
because
$request->request->set
can't work properly if your POST data from form are in bag (parameterbag)
no entity managers, no services, no listeners...
hope it helps.

symfony 2 cant save to database correctly

To be short
my entity have this:
/**
* #ORM\ManyToOne(targetEntity="Classes", inversedBy="")
* #ORM\JoinColumn(name="class_id", referencedColumnName="id")
*/
protected $class;
i have no inverse relation, because i don't need it.
and i try to do this:
$class = $this->getDoctrine()->getRepository('TomasRClassBundle:Classes')->find($_POST['fighter']['class']);
$item = new Fighter();
$item->setName($_POST['fighter']['name']);
$item->setClass($class);
//if i var_dump here $item->getClass(), its there, class where set correctly
$item->setBelongsTo(1);
$em = $this->getDoctrine()->getManager();
$em->persist($item);
$em->flush();
and after that in database, in class_id i have null.. however if I edit it with form, this is form field:
$builder->add('class', 'entity', array('class' => 'TomasRClassBundle:Classes','property' => 'name'));
and after i submit the form i do:
$item = $this->getDoctrine()->getRepository('TomasRClassBundle:Fighter')->find($id);
$type = new FighterForm();
$form = $this->createForm($type, $item);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($item);
$em->flush();
//return $this->redirect($this->generateUrl('admin_fighter_list'));
}
and now the class_id field in db is set correctly.
i could hard code my solution, but i wanna know what i am doing wrong?
Thanks in advance, i know it might be a bit hard to read, sorry for that :)

Categories