So I'm pretty new to Symfony and I'm trying to have the controller build slightly different forms based on controller actions. Right now, I have this
//in Controller
public function addLocationEntryAction(Request $request)
{
    $entry = new Entry();
    $form = $this->get('form.factory')->create(new EntryType('addLocation'), $entry);
    return $this->render('OOTNBlogBundle:Blog:addEntry.html.twig', array(
        'form' => $form->createView()
    ));
}
public function addArticleEntryAction(Request $request)
{
    $entry = new Entry();
    $form = $this->get('form.factory')->create(new EntryType('addArticle'), $entry);
    return $this->render('OOTNBlogBundle:Blog:addEntry.html.twig', array(
        'form' => $form->createView()
    ));
}
And
//in EntryType
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('title',      'text')
        ->add('continent',  'text', array('required' => false))
        ->add('country',    'text', array('required' => false))
        ->add('category',   'text', array('required' => false))
        ->add('author',     'hidden')
        ->add('type',       'hidden')
        ->add('text',       'textarea')
        ->add('post',       'submit')
    ;
}
I'd like to pass an option from the controller in buildForm, so that I can do something like this:
public function buildForm(FormBuilderInterface $builder, array $options, $option)
{
    $builder
        ->add('title',      'text')
    ;
    if($option == 'addLocation')
    {
        $builder
            ->add('continent',  'text', array('required' => false))
            ->add('country',    'text', array('required' => false))
        ;
    }
    elseif($option == 'addArticle')
    {
        $builder
            ->add('category',   'text', array('required' => false))
        ;
    }
    $builder
        ->add('author',     'hidden')
        ->add('type',       'hidden')
        ->add('text',       'textarea')
        ->add('post',       'submit')
    ;
}
How do I do this? I've checked out the Symfony doc and similar questions on here but nothing seems to be quite fitting for my case. I don't know.
There is no need to create an additional param, just use options to pass custom data. In the following example, I made age attribute mandatory, you could have it optional or specify default value. Read more about OptionsResolver here
class ExampleType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        var_dump($options['age']);
    }
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setRequired(array(
            'age'
        ));
    }
}
Create:
$form = $this->get('form.factory')->create(new ExampleType(), $entry, array(
    'age' => 13
));
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With