Search code examples
symfony1symfony-1.4

Dynamically change the embedd form field value - Symfony 1.4


I have a question about Symfony embed form. Basically i have form called Media. Media field will save user image, product image and etc.

Media Scheme:

Media:
  actAs:
    Timestampable: ~    
  columns:
    entity:
      type: string(60)
      notnull: true
    entity_id:
      type: bigint(20)
      notnull: true
    file:
      type: string(255)
      notnull: true 

Here,

  • entity = product or user or etc
  • entity_id = product_id or user_id or etc

So, i want to change entity values dynamically depends upon where i am calling these form.

 $this->embedForm('media', new MediaForm());

So, i want to change the field value from here or Advice me if there is any better way.


Solution

  • In order to save a Media object an id is needed, so save can be done after the "parent" object was saved. I think the best option you have is the saveEmbeddedFroms() method (in the form which the MediaForm is embedded into):

    public function saveEmbeddedForms($con = null, $forms = null)
    {
      if (isset($this->embeddedForms['media']))
      {
        $mediaForm = $this->getEmbeddedForm('media');
    
        if ($mediaForm instanceof MediaForm && $mediaForm instanceof sfFormDoctrine)
        {
          $mediaFrom
            ->getObject()
            ->set('entity', get_class($this->getObject()))
            ->set('entity_id', $this->getObject()->get('id'))
          ;
        }
      }
    
      parent::saveEmbeddedForms($con, $forms);
    }
    

    Actually you can put this into the BaseFormDoctrine class as well, so every doctrine form which has an embedded MediaForm will be saved correctly.

    Edit: Finally sfFormObject works for me

    public function saveEmbeddedForms($con = null, $forms = null)
    {
      if (null === $con)
      {
      $con = $this->getConnection();
      }
    
      if (null === $forms)
      {
      $forms = $this->embeddedForms;
      }
    
      foreach ($forms as $form)
      {
    
        if ($form instanceof sfFormObject)
        {
          $form->getObject()->set('entity', get_class($this->getObject()))->set('entity_id', $this->getObject()->get('id'));
        }    
    
    
      }
      return parent::saveEmbeddedForms($con, $forms);
    }