1

I have a dynamic select tag in my index.twig The code of the select is

 <select name="portfolio" style="width: 265px; height:28px;">
   <option selected="selected" value="default">Switch Your Portfolio</option>
   {% for portfolio in portfolios %}
      <option value={{ portfolio.id }}>{{ portfolio.portfolioName }}</option>
   {% endfor %}
 </select>

Now I have SwitchPortfolioType and I want to create this dynamic select inside my Type

class SwitchPortfolioType extends AbstractType
{
   public function buildForm(FormBuilder $builder, array $options)
   {
    $builder
    ->add('availability', 'choice', array(
        'choices'   => array(
            //dynamic options here
     ),
            'empty_value' => 'Switch your Portfolio',
    ));
   }
}

How can I do this in Symfony2

3 Answers 3

3

I have implemented the code in our project in this way.....

class SwitchPortfolioType extends AbstractType
{
   public function buildForm(FormBuilder $builder, array $options)
   {

       $builder
            ->add('name')
            ->add('description')
            ->add('parentid', 'entity', array('class'=>'MusicCoreBundle:MusicCategory',
                'property'  => 'name',
                'required'  => false,
                'query_builder' => function(EntityRepository $er) {return $er->createQueryBuilder('s')->orderBy('s.name', 'ASC');},
                'empty_value' => 'No category'));

   }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Create a constructor that takes an array as an argument for the SwitchPortfolioType class:

public function __construct($myArray)
{
    $this->myArray = $myArray;
}

And, in your controller, pass it your dynamic array when you create the form object:

$form = $this->createForm(new SwitchPortfolioType($myArray), $entity);

Now you can use the array inside the form type with $this->myArray.

Comments

0

See in this document page, You can set dynamic data by using FormEvents::PRE_SET_DATA in form builder area.

http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#how-to-dynamically-generate-forms-based-on-user-data

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.