title: Symfony2: Dynamic defaults for a custom form type?
body: <p>I use a <code>entity</code> form type to provide a list of <code>Position</code> entities in a form. I use it often enough (each with the same "setup" code to customize it) that I've decided to make a custom form type from it for better re-use.</p>
  
  <p>Here's the current form type:</p>
  
  <pre><code>class PositionType extends AbstractType
  {
      private $om;
  
      public function __construct(ObjectManager $om, $mode)
      {
          $this-&gt;om = $om;
      }
  
      public function buildForm(FormBuilderInterface $builder, array $options)
      {
      }
  
      public function setDefaultOptions(OptionsResolverInterface $resolver)
      {
          // I need to pass "mode" as an option when building the form.
          $mode = ???
          $query_builder = function (EntityRepository $em) use ($mode) {
              // Limit the positions returned based on the editing mode
              return $em
                  -&gt;createQueryBuilder('Position')
                  -&gt;orderBy('Position.name')
                  -&gt;leftJoin('Position.type', 'Type')
                  -&gt;andWhere('Type.id IN (:ids)')
                  -&gt;setParameter('ids', Type::typesForMode($mode))
              ;
          };
  
          $resolver
              -&gt;setRequired(array('mode'))
              -&gt;setDefaults(array(
                  'label' =&gt; 'Position',
                  'class' =&gt; 'AcmeBundle:Position',
                  'property' =&gt; 'name',
                  'query_builder' =&gt; $query_builder,
                  'empty_value' =&gt; '',
                  'empty_data' =&gt; null,
                  'constraints' =&gt; array(
                      new NotBlank(),
                  ),
              ))
          ;
      }
  
      public function getParent()
      {
          return 'entity';
      }
  
      public function getName()
      {
          return 'position';
      }
  }
  </code></pre>
  
  <p>Don't worry about the specifics in the query builder, that doesn't matter. The part that does matter is I'm trying to use a form type option in the query builder.</p>
  
  <p>How can I do this? The problem is I can't use <code>$mode</code> (the option I want to pass to alter the query builder) in <code>setDefaultOptions</code>.</p>
  
  <p>I was beginning to look for a way to set the query builder from inside <code>buildForm</code> but I'm not sure I can do that.</p>