Code snippets for symfony 1.x

Navigation

auto save embedded form foreign key

public function saveEmbeddedForms($con = null, $forms = null)
  {
    if (is_null($con))
    {
      $con = $this->getConnection();
    }
 
    if (is_null($forms))
    {
      $forms = $this->embeddedForms;
    }
 
    foreach ($forms as $form)
    {
      if ($form instanceof sfFormDoctrine)
      {
        // The magic start here
        $field_name  = $this->getObject()->getTable()->getTableName().'_id';
        if($form->getObject()->contains($field_name)) {
          $method_name = 'set'.sfInflector::camelize($field_name);
          $form->getObject()->$method_name($this->getObject()->getId());
        }
        // Here it ends
        $form->getObject()->save($con);
        $form->saveEmbeddedForms($con);
      }
      else
      {
        $this->saveEmbeddedForms($con, $form->getEmbeddedForms());
      }
    }
 
by Marc Carlucci on 2009-09-01, tagged doctrine  embed  embedform 

Comments on this snippet

gravatar icon
#1 david epely on 2010-03-01 at 03:18

good, I made something more specific but the idea is the same ... But If you work on the child while saving you'll got problems : For example :

First you have MyObjectForm embedding MyChildForm (in relation one-to-one). And in MyObject : public function save() { $this->MyChild->something = 'too bad'; }

At the end you'll not be able to save MyObject.

gravatar icon
#2 Anonymous on 2010-05-01 at 10:48

I used embedForm for a 1:1 relation and it didn't saved the dependent object, even when it's supposed to, isn't it. this piece of code saved my ass. Fot those who need to use this snippet: don't forget to put it extending your forms and not in the sfFormObject or you'll get some limitations.

Thanks Marc

gravatar icon
#3 Fabian Barrera on 2010-05-01 at 10:50

Last comment is mine.