Wizard
Wizard

Reputation: 11295

Symfony2 update row from array

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; 

Upvotes: 0

Views: 1113

Answers (1)

Athlan
Athlan

Reputation: 6629

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

Upvotes: 2

Related Questions