Snippet: Symfony Forms - Accessing the Object in a Form

Perusing my Google Analytics data shows up some interesting results. For starters the top search query which sends people to my blog is "symfony accessing object in a form". This has been consistent for several months, but there is no article on my blog which answers that question. I imagine this must be very frustrating for people so it's about time I added the answer here as a snippet.

// lib/form/MyObjectForm.class.php
public function configure()
{
  $myobject = $this->getObject();
}

In a form class $this refers to the form. Both sfFormPropel and sfFormDoctrine have the method getObject() which will return the object associated with the form. In Symfony, the form ALWAYS has an object associated with it, as even if you don't pass it one, the form setup will create and associate a new (unsaved) object.

On the default values snippet, I was asked how to set default values for a form in an action. If you want default values for the form, you can set them in the form class as explained in that snippet, or if you want the object to have a default value, override the model with constants (or provide them in your schema).

If you want to pass preset values to the form in your actions.class.php you can do so when you create the form. The constructors for both Propel and Doctrine forms take an object as an argument which the ORM will then use as the associated object. Therefore you can create a new object, assign the values you want and then pass the object to the form as shown below:

<?php
    //apps/myApp/modules/myModule/actions/actions.class.php
   public function executeMyAction(sfWebRequest $request)
  {
    // create an object for the form
    $myobject = new MyObject();
   // object already has default values, or to set additional ones:
    $myobject->setValue('Default');
  // instantiate the new form with it's object
    $this->form = new MyObjectForm($object);
  }
?>

Update: It's probably worth adding, if you're looking to access the user object specifically, I have more detail on that in another snippet which deals with the user object.

Please let me know if you have any problems with these snippets, or if you find them useful! If you are someone who has come to my blog through this or a similar search query, drop me a comment and let me know if I've answered the question, or if there is more that I could help with.

A Note on Snippets: When using frameworks such as Symfony it is often the simplest pieces of code which are the hardest to either find or remember. These snippets are placed here for my own reference and will hopefully be useful to others. If you find them useful or have any suggestions, please let me know.