Proper way to update class object in db using symfony2 + doctrine + form? -


i have simple class:

class type {     /**      * @orm\column(type="integer")      * @orm\id      * @orm\generatedvalue(strategy="auto")      */     private $id;      /**      * @orm\column(type="string", length=15)      */     private $name;      ...  } 

and have 'type' objects in database. so, if want change 1 of them, create new controller rule (like /types/edit/{id}) , new action:

public function typeseditviewaction($id) {        ...      $editedtype = new type();      $form = $this->createformbuilder($editedtype)         ->add('name', 'text')         ->add('id', 'hidden', array('data' => $id))         ->getform();      // send form twig template     ... } 

after that, create controller rule (like /types/do_edit) , action:

public function typeseditaction(request $request) {        ...      $editedtype = new type();      $form = $this->createformbuilder($editedtype)         ->add('name', 'text')         ->add('id', 'hidden')         ->getform();      $form->bind($request); // <--- error there !!!      // change 'type' object in db     ... } 

and found small problem there. Сlass 'type' doesn't have аuto-generated setter setid() , on binding got error.

neither property "id" nor 1 of methods "setid()", "__set()" or "__call()" exist , have public access in class "lan\csmbundle\entity\type". 

now, remove 'id' field symfony2 form object ($form) , transmit manually template. @ second controller's action have $form object , 'id'-field apart. don't know 'proper'-way doing (updating 'type' class). please help.

symfony has integrated paramconverter automatically fetches entity database , throws exception ( can catch in listener ) if entity not found.

you can handle , post requests in 1 controller method.

make sure have public getters , setters properties in entity.

i added annotations make routing clearer , still have working example.

use vendor\yourbundle\entity\type; use sensio\bundle\frameworkextrabundle\configuration\route; use sensio\bundle\frameworkextrabundle\configuration\method;  // ...  /**   *  @route("/edit/{id}", requirements={"id" = "\d+"})  *  @method({"get", "post"})  */ public function editaction(request $request, type $type) {         $form = $this->createformbuilder($type)         ->add('name', 'text')         ->add('id', 'hidden')         ->getform()     ;      if ($request->ismethod('post')) {          $form->bind($request);           if ($form->isvalid())          {               $em = $this->getdoctrine()->getentitymanager();               $em->flush();          // entity persisted , managed doctrine.                // return success response          }     }      // return form ( include errors if validation failed ) } 

i suggest should create form type further simplify controller.


Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -