Symfony2 update row from array - symfony

I want update row setting new values from array, now Iset one by one aribute:
$em = $this->getDoctrine()->getManager();
$company = $em->getRepository('CatalogWebBundle:ComCompany')
->findOneBy(
array('cmpCode' => $id)
);
$company->setCmpName($_POST['name']);
$company->setCmpCode($_POST['code']);
$em->flush();
Maybe exist solution to set all atributes from array, some like this ?
$company = $_POST;

Consider using Symfony Form and use like this:
<?php
$request = $this->getRequest(); // or inject Request to the action method like myAction(Request $request)
$em = $this->getDoctrine()->getManager();
$company = $em->getRepository('CatalogWebBundle:ComCompany')
->findOneBy(
array('cmpCode' => $id)
);
$form = $this->createForm('formName', $company);
$form->handleRequest($request);
if($form->isValid()) {
// if you want, you can get entity here,
// but passing an entity in 2nd param of createForm
// provides automatic binding data
$data = $form->getData();
$em->flush();
// do some action after submitting form...
return $this->redirect($this->generateUrl('companies'));
}
Read more about creating forms:
http://symfony.com/doc/current/book/forms.html
And about regitering forms as services for futher use named form in createForm('NAME_HERE', $bindObjectHere):
http://symfony.com/doc/current/book/forms.html#defining-your-forms-as-services

Related

Array Collection persistence on symfony2

i'm using a event listener on the submit of a form where, i need to catch a xml file, open it and extract his contents, put it on an entity and add that to a collection from other entity.
right now this is works:
$builder->addEventListener(FormEvents::SUBMIT, function(FormEvent $event){
$entity = $event->getData();
if($entity){
$parent = $event->getForm()->getParent()->getData();
$gpx = $entity['gpx'];
if($gpx){
$xmlGpx = simplexml_load_file($gpx);
foreach ($xmlGpx->wpt as $pt) {
$point = new MonitoringPoint();
$point->setPoint(new \CrEOF\Spatial\PHP\Types\Geometry\Point((string) $pt['lat'], (string) $pt['lon']));
$point->setAltitude((float) $pt->ele);
$point->setDate(($pt->time->count() ? new \DateTime((string)$pt->time) : null ));
$point->setAccuracy((float) $pt->hdop);
$parent->addMonitoringPoint($point);
}
$fileName = $gpx->getClientOriginalName();
$directory = __DIR__.'/../../../../web/uploads/';
$date = new \DateTime();
$newFileName = md5($gpx->getClientOriginalName().$date->getTimestamp());
$gpx->move($directory, $fileName);
$fs = new Filesystem();
$fs->rename($directory.$fileName, $directory.$newFileName.'.gpx');
$parent->setGpx($newFileName.'.gpx');
}
}
});
$parent is an instance of Monitoring, if i open $parent i will see that the $point vars has been added on the collection monitoringPoints of the variable, and the gpx too.
but then i go so see the entity right before been persisted, inside newAction
$entity = new Monitoring($params);
$form = $this->createForm(new MonitoringType(), $entity, array(
'action' => $this->generateUrl('my_route'),
'method' => 'POST',
));
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
dump($entity);die;
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
}
and the collection is empty! but the gpx attribute contains the right value.
does the collection gets reseted?
i had to pass the points in to an array within the session, still think that was not the best option, but worked
$array = [];
foreach ($xmlGpx->wpt as $pt) {
$point = new MonitoringPoint();
$point->setPoint(new \CrEOF\Spatial\PHP\Types\Geometry\Point((string) $pt['lat'], (string) $pt['lon']));
$point->setAltitude((float) $pt->ele);
$point->setDate(($pt->time->count() ? new \DateTime((string)$pt->time) : null ));
$point->setAccuracy((float) $pt->hdop);
$point->setMonitoring($parent);
array_push($array, $point);
}
$session = new Session();
$session->getFlashBag()->add('array', $array);
in the newAction:
$em = $this->getDoctrine()->getManager();
$session = new Session();
$array = $session->getFlashBag()->get('array');
foreach($array[0] as $point) {
$point->setMonitoring($entity);
$entity->addMonitoringPoint($point);
}
$em->persist($entity);
$em->flush();
dont know why the array got reseted when it comes to the controller, cause i had setted the points in the entity during the submit

Symfony2 handleRequest with PUT request

I have some trouble with handleRequest:
Here is my code:
public function putAssetAction(Request $request, $id){
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository( 'BudgetBundle:Asset' )->find( $id );
$form = $this->createForm( new AssetType(), $entity, array('method' => 'PUT') );
$form->handleRequest($request);
The problem is that form data are correct, but $form->isValid() return false because isSubmitted() is false
But $form->bind() is also not working, because it's a PUT request, and when I do bind($request) then $form->getData() returns null.
I'm using this with FosRestBundle and Backbone, and for testing request I'm using chrome extension postman.
You can try submit() instead of handleRequest(), eg:
$form->submit($request);

symfony doctrine update from form

I'm stuck since this morning with the update of an entity.
Don't know what I'm missing, pretty sure this is a newbie mistake.
I'm just trying to update something via a form.
The controller:
public function editAction($pid, $plid, Request $request)
{
$plan = new Plan();
$form = $this->createForm(new PlanType(), $plan);
$plan = $this->getDoctrine()->getRepository('QArthFrameworkBundle:Plan')->findOneByPlid($plid);
$project = $this->getDoctrine()->getRepository('QArthFrameworkBundle:Project')->findOneByPid($pid);
$form->handleRequest($request);
if ($request->getMethod() == 'POST') {
$em = $this->getDoctrine()->getManager();
$em->flush();
return $this->redirect($this->generateUrl('qarth_framework_plan_edit', array('pid' => $pid, 'plid' => $plid)));
}
return $this->render('QArthFrameworkBundle:Pages:plan_edit.html.twig', array(
'plan' => $plan,
'project' => $project,
'form' => $form->createView(),
));
}
The form:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name');
$builder->add('description', 'textarea');
}
The Entity : http://pastebin.com/bTqKehyQ
With the profiler I can see that my post parameters are well posted
plan {"name":"fsggsfgsf","description":"gsfgsfgsf","_token":"7d089aca0203c60fe1e617488e532ac966101440"}
But I can't see any trace of an update query or something else.
If you have an idea, it will be great!
Many thanks,
Ben
Need to pass the queried plan to the form.
public function editAction($pid, $plid, Request $request)
{
$plan = $this->getDoctrine()->getRepository('QArthFrameworkBundle:Plan')->findOneByPlid($plid);
$project = $this->getDoctrine()->getRepository('QArthFrameworkBundle:Project')->findOneByPid($pid);
// Create a new one if not found
if (!$plan) $plan = new Plan();
// Build your form using queried or new plan
$form = $this->createForm(new PlanType(), $plan);
$form->handleRequest($request);
// Checks for POST as well as validity
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($plan); // To handle new plans, no impact for existting plans
$em->flush();
// Rest is the same

Symfony adding extra fields by CreateAction

I have a createAction for a Symfony request.
How can I add some values in another entity, by creating a new Entity value.
See the following foreach part; whats wrong with it?
public function createAction(Request $request)
{
$entity = new FooType();
$form = $this->createForm(new FooTypeType(), $entity);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
$entities = $em->getRepository('OtherBundle:Lists')->findAll();
foreach($entities as $list){
$manager = $this->getDoctrine()->getManager();
$listValue = new ListValue();
$listValue->setSpecification( new ListsType(), $list );
$manager->persist($listValue);
$manager->flush();
}
return $this->redirect($this->generateUrl('foo_foobar_show', array('id' => $entity->getId())));
}
if you have a proper association mapping between your entities and use Doctrine's persist option for the cascade operation you won't have to persist your related entities explicitly.
You can in this case ommit
$manager->persist($listValue);
Furthermore for performance reasons make sure you flush your entityManager only once - you don't need to flush more than once often except in case you need the auto-generated ID of a newly persisted entity!
create a new method in your repository ( addListsToEntity() ) or in a manager class for adding your lists!

symfony2 don't validate file upload on update

I want to update the single entity field using ajax. Basically I don't have form, Simply I am triggering ajax by clicking link passing id and value. But I have mutiple file fields in entity form. So while I update the entity PrePersist and PostPersist functions are triggering for file upload. I don't want to do this on this update.
My Controller Action
public function ajaxupdateAction(Request $request){
$data = $request->query->get('data');
$id = $data['id'];
$em = $this->getDoctrine()->getManager();
$entry = $em->getRepository('RootContestBundle:Entry')->find($id);
if (!$entry) {
throw $this->createNotFoundException('Unable to find Entry entity.');
}
$form = $this->createFormBuilder(array('id' => $id,'is_liked'=>true))
->add('id', 'hidden')
->add('is_liked','hidden')
->getForm();
$entry->setIsLiked(true);
$form->bind($this->getRequest());
$em->persist($entry);
$em->flush();
return new JsonResponse(array('reverse'=>'dislike'));
}
What I am doing wrong, How can I solve this !
Here you got an documentation about the form event subscribers:
http://symfony.com/doc/2.0/cookbook/form/dynamic_form_generation.html
Use the postBind event.
Then check if the form isValid()
If it is valid call your service responsible for file upload.
Here is how I did this:
public function postBind(FormEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
$file = $form->get('upload')->getData();
if($file && $form->isValid())
{
$result = $this->upload->uploadFile($file);
$data->setUpload($result);
}
$event->setData($data);
}
My method has the upload service injected by DI and assigned to variable $this->upload.

Resources